From: Rick DeNatale Date: 2007-10-26T03:32:43+09:00 Subject: Re: Need help understanding metaclassing On 10/25/07, Chris Czub wrote: > I've been reading lots of Ruby tutorials trying to figure out > metaclassing - the one that got me closest was Why?s poignant guide to > Ruby, but I'm still struggling over some of the Ruby-specific syntax. > > I attached a class I've been writing that needs to be highly extensible, > and it's loaded with comments I wrote to try to understand each part of > it. If any part of the comments are wrong, it would be nice to have my > misconceptions cleared up. I've only been using Ruby for a day and, wow. > > Here's the part I'm having the hardest time figuring out, and Why?s > guide kind of skipped over it: > > metaclass.instance_eval do > define_method( a ) do |val| > @attribs ||= {} > @attribs[a] = val > end > end > > So, I understand that the block inside the instance_eval will be > executed in the instance of the object(meaning when I create a new > object, right?) Wrong! the block argument to instance_eval is evaluated right away, in the context of metaclass. The context is missing but I'm assuming that this is inside a class definition, and metaclass has been defined as a method to return the singleton class. So lets say we had: class Foo metaclass #=> the singleton class of Foo. metaclass.instance_eval do # Inside this block self is bound to the singleton class of foo define_method(:bar) {"bar"} end end This has the same effect as class Foo def self.bar "bar" end end I.e. it defines a class method of Foo. Now I'd usually use class_eval, or module_eval which do the same thing but only work if the receiver is a class/module. > However, I don't understand the next part. define_method is a method > call to the method that is defined further down, right? But what is the > " do |val|" after the method call, and what is the point of the two > lines after that? David A. Black has already answered this. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/