From: "David A. Black" Date: 2007-10-26T02:44:45+09:00 Subject: Re: Need help understanding metaclassing Hi -- On Fri, 26 Oct 2007, 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?) > > 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? > > If anyone could explain this to me, I would be greatly indebted. The do/end sequence is a code block. Have a look at some of the tutorials -- they'll definitely talk about code blocks. When you pass a code block to define_method, the code block serves as the method body for the method you're defining. The lines after that assign an empty hash to @aattribs (except if @attribs is already set, the assignment is skipped; that's what ||= does), and sets the value of @attribs[a] to val. val is the block parameter, and will therefore also be a method parameter for the new method. David -- Upcoming training by David A. Black/Ruby Power and Light, LLC: * Advancing With Rails, Edison, NJ, November 6-9 * Advancing With Rails, Berlin, Germany, November 19-22 * Intro to Rails, London, UK, December 3-6 (by Skills Matter) See http://www.rubypal.com for details!