class Foo;end
=> nil
f = Foo.new
=> #Foo:0x10189038
def f.bar; puts “ja”; end
=> nil
f.bar
ja
=> nil
f.dup.bar
NoMethodError: undefined method `bar’ for #Foo:0x101832f0
from (irb):5
f.clone.bar
ja
=> nil
“While clone is used to duplicate an object, including its internal state,
dup typically uses the class of the descendent object to create the new
instance.” http://www.ruby-doc.org/docs/rdoc/1.9/classes/Object.html#M000889
I’m interested in the reasoning behind this.
I think the rationale is singleton methods being part of internal state.
I’m actually depending on this behavior for stripping singleton methods
from potentially dangerous objects so if this is to be changed I would
need an alternative way to clone objects without their singleton methods.
“While clone is used to duplicate an object, including its internal
state,
dup typically uses the class of the descendent object to create the
new
instance.” http://www.ruby-doc.org/docs/rdoc/1.9/classes/Object.html#M000889
I’m interested in the reasoning behind this.
I think the rationale is singleton methods being part of internal state.
I’m actually depending on this behavior for stripping singleton methods
from potentially dangerous objects so if this is to be changed I would
need an alternative way to clone objects without their singleton
methods.
Sounds reasonable. Still something strikes me as odd: #class still
returns the original class. Why doesn’t it return the singleton class?
class Foo;end
=> nil
f=Foo.new
=> #Foo:0x10189578
f.class
=> Foo
f.class.id
=> 135026484
def f.bar; “bar”;end
=> nil
f.bar
=> “bar”
f.class
=> Foo
f.class.id
=> 135026484
^^^^^^^^^
One could expect something different here. Any comments?
Sounds reasonable. Still something strikes me as odd: #class still
returns the original class. Why doesn’t it return the singleton
class?
#class always return the class of the object.
One could expect something different here. Any comments?
class A
end
a = A.new
b = A.new
class << a
def a
end
end
p a.class == b.class
Now do you really expect ‘false’ ?
Well, I don’t since I know it’s done otherwise in Ruby. But, one could
reasonably. Still (A === a) == true and (A === b) == true. I just wanted
to point out that although there is this anonymous class of the instance
it’s not accessible in any way I know of (other than iterating through
ObjectSpace maybe).
An alternative would be that “class << a” could return this singleton
class…