From: Chris Pine Date: 2002-12-12T01:51:47+09:00 Subject: Re: all the pretty evals... ----- Original Message ----- From: "Mauricio Fern�ndez" [snip] Don't forget irb(main):001:0> class Foo irb(main):002:1> end nil irb(main):003:0> Foo.instance_eval { define_method("bar") {"bar"} } # irb(main):004:0> p Foo.new.bar "bar" nil ---------------------------- Now this totally confuses me... So these two are the same Foo.module_eval 'def bar; "bar"; end' Foo.module_eval {define_method("bar"){"bar"}} ...but these two are different... Foo.instance_eval 'def bar; "bar"; end' Foo.instance_eval {define_method("bar"){"bar"}} ...since one defines a class method and the other defines an instance method. Clearly, I understand *how* these work (i.e. what these lines of code do); I'm asking *why* they work (what the underlying principle and reasoning behind these is). ---------------------------- [snip] > class Foo > end > > foo = Foo.new > > # Is this the only way to get this class? AFAIK yes. > klass = class << foo; self; end irb(main):005:0> foo = Foo.new # irb(main):006:0> klass = class << foo; self; end Foo ---------------------------- My irb gives something a little more clear: irb(main):004:0> klass = class << foo; self; end => #> ---------------------------- irb(main):023:0> klass.new.fubar TypeError: can't create instance of virtual class ---------------------------- Virtual class? I think this is what I am not understanding very clearly. ---------------------------- define_method belongs to Module, you're calling it in an instance of Foo.. > ...Well, I understand why that didn't work... ---------------------------- Well, I understood why that didn't work... :) ---------------------------- > I guess my question is, why does... > > foo.instance_eval 'def bar; "bar"; end' > > ...work? What does that even mean? ---------------------------- This is creating a virtual class, then? Why is there no way normal way to get an object's virtual class? Any method I can think of to do this was inadvertently *create* a virtual class if there wasn't one already, but I'd prefer one which simply returns nil if there wasn't one. ---------------------------- > Also, why (in the last working snippet) > does foo.class give Foo, rather than klass? As for foo.class == Foo, it looks like #class (aka #type) returns the Class the object was instanciated from, not the singleton class. Otherwise you'd not be able to do 'object.class.new' or the like. ---------------------------- Yes, I can see that. :) I'm asking how this sort of singleton class differs from 'regular' inheritance. What is the theory/rationale/model behind this? (If I asked why there was a law against killing people, I wouldn't feel my question was answered if someone said, "Because, you see, killing is illegal," and then referred me to the specific law. I'd be looking for something more like, "Because killing is wrong, and because making killing illegal makes it illegal for others to kill you.") Thanks, Chris