"Self" Reference

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
.
.
.
buddy_list[0].type == Guy

Is this possible?

Nathan O. 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

Nathan O. wrote:

.
.
.
buddy_list[0].type == Guy

Is this possible?

My word, the possibilites if you could! You could change an object’s
“class” on the fly, hence easy implemention “roles”. I think of this as
the “soul” of an object. What are other implications of soul shifting?

T.

On Jul 13, 2006, at 7:00 PM, Marcin MielżyÅ?ski wrote:

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).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs