David Masover
8/2/2008 3:45:00 AM
On Friday 01 August 2008 22:04:01 markbuckingham@gmail.com wrote:
> Basically, I'm trying to create a Info object, and do various things
> to that new object within the block.
What block? You mean this one?
> info :Bob do |i|
> i.address "123 Main St."
> i.city "Boston, MA"
> end
But the "info" method you've defined doesn't do anything with that block:
> def info(name)
> Info.new(name)
> end
The block has to be used somewhere within the body of that object. (Trying not
to be too offensive here, but you have exactly zero code in place to do
anything with the block -- which is why nothing happens to the block.)
What you probably want is either to turn it into a local variable:
def info(name, &block)
p block
Info.new(name, &block)
end
Of course, you'd have to change the constructor, too:
def initialize(name)
@name = name
yield self
end
It's probably easier just to do this:
def info(name)
i = Info.new(name)
yield i
i
end
Or, if you have at least Ruby 1.8.7, this should work:
def info(name)
Info.new(name).tap do |i|
yield i
end
end
For what it's worth, one of the benefits of open source is, if you're
wondering "How did they do that??", you can find out. Here's a snip from
create_table:
def create_table(table_name, options = {})
table_definition = TableDefinition.new(self)
...
yield table_definition
...
end
Object#tap is also a nice illustration of how blocks can work. It's actually
written in C, but here's how I fake it on 1.8.6:
class Object
def tap
yield self
self
end
end