Logan Capaldo
7/14/2006 3:46:00 AM
On Jul 13, 2006, at 7:00 PM, Marcin Mielzynski wrote:
> Nathan Olberding wrote:
>> Is it possible to define new classes that behave like standard
>> datatypes when an instance is referred to? For example:
>> class ListOfBuddies
>> def initialize
>> self = []
>> self.push(Guy.new(name))
>> end
>> end
>> buddy_list = ListOfBuddies.new
>
> Then, definitely, inheritance is the right choice:
>
> class ListOfBuddies < Array
> def initialize
> self.push(Guy.new(name))
> end
> end
>
> buddy_list = ListOfBuddies.new
>
>
> lopex
>
Ehhh, I wouldn't necessarily choose inheritance. It depends on what
he's doing but ListOfBuddies doesn't strike as having an isa
relationship with an Array. I personally would choose delegation:
Couple of ways to this:
require 'delegate'
class ListOfBuddies < DelegateClass(Array)
def initialize
__setobj__([])
push Guy.new(name)
end
end
or
require 'forwardable'
class ListOfBuddies
extend Forwardable
def initialize
@list = []
push Guy.new(name)
end
def_delegators :@list, :push, :[]
end
The last is my personal favorite. You get to pick exactly what
methods get delegated to the delegate and unlike inheritance you
don't accidently pull in stuff that could possibly kill your
invariants. (esp. with core classes like Array, they have a _lot_ of
methods).