class SimpleDelegator


Unique: 6
Non-Nil: 7
Elements: 8
Unique: 4
Non-Nil: 4
Elements: 4
Prints:
puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
puts
puts s.stats(%w{James Edward Gray II})
s = Stats.new
end
end
“ Unique: #{@source.uniq.size}n”
“ Non-Nil: #{@source.compact.size}n” +
“Elements: #{@source.size}n” +
@source.__setobj__(records)
def stats(records)
end
@source = SimpleDelegator.new([])
def initialize
class Stats
SimpleDelegator’s delegation object can be changed at any time.
Here’s a simple example that takes advantage of the fact that<br><br>SuperArray.new()[0] #=> 2
end
end
super + 1
def [](*args)
class SuperArray < SimpleDelegator
the object being delegated to.
is a subclass of Delegator to call super to have methods called on
A SimpleDelegator instance can take advantage of the fact that SimpleDelegator
decorated_user.__getobj__ #=> #<User: …>
decorated_user.birth_year #=> 1989
decorated_user = UserDecorator.new(User.new)
end
end
born_on.year
def birth_year
class UserDecorator < SimpleDelegator
end
end
Date.new(1989, 09, 10)
def born_on
class User
#__setobj__.
and even to change the object being delegated to at a later time with
delegate all supported method calls to the object passed into the constructor
A concrete implementation of Delegator, this class provides the means to
#

def __getobj__

Returns the current object method calls are being delegated to.
def __getobj__
  @delegate_sd_obj
end

def __setobj__(obj)


puts names[1] # => Sinclair
names.__setobj__(%w{Gavin Sinclair})
puts names[1] # => Edward
names = SimpleDelegator.new(%w{James Edward Gray II})

Here's an example of changing the delegation object.

to objects of the same type as the original delegate.
to change. Because of this, you probably only want to change delegation
It's important to note that this does *not* cause SimpleDelegator's methods

Changes the delegate object to _obj_.
def __setobj__(obj)
  raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
  @delegate_sd_obj = obj
end