Code Blocks in Ruby

Posted by science on July 29, 2007

Godel Escher Bach
Here’s an interesting Rubyism.. Basically when you build an iterator, you can invisibly pass a ‘block’ of code (which is an object) into your method. But what if you want to delegate the iteration to another method? You could create a duplicate loop structure in the primary method, but that’s too rigid - you can’t just change the loop/block on the ends..
So here are two examples, the first shows the way you might accomplish this in the “rigid” manner. The second shows the way Ruby lets you do it right:

# hard way
def outer(val)
  inner(val) do |val1, val2|
    yield val1, val2
  end
end

def inner(val)
  yield val, 'extra var'
end

# run-time here
outer('hello') do |val, val1|
  puts "#{val}::#{val1}"
end
# easy way
def outer1(val, &block)
  outer2(val, &block)
end

def outer2(val)
  yield val, 'extra var'
end
#run time here
outer1('world') do |val, val1|
  puts "#{val}::#{val1}"
end

The second accepts a “&block” parameter which has to be the last parameter. This substitutes for the block that the calling method encases the method call in. You can see this allows us to eliminate the rigidity of having to mimic the loop structure in the intermediate method.. Also note that we don’t have to receive the &block explicitly in outer2 because Ruby takes care of block handling automatically, if you use a “yield” statement or equivalent - you only need to declare it explicitly when you want to pass the block around or do something else to (like serialize it!)..

I like the syntax for this anyway.. No fuss no muss..

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments