11
February
2007

Silly little Ruby let0

It occurred to me yesterday, while playing with the Ruby script I was writing, that it would be useful to have a let facility in Ruby, which would enable the following code

def foo
  # do something really exciting with the object 'master_foo'
  # now...
  master_foo.select { |x| x>3 }.let do |mf|
    puts "#{mf}, #{mf.length}"
  end
end

What is it good for? Well, instead of introducing a new local variable and using assignment to hold a temp value (like the result of the select call above), we can add a let method that simply yields itself to the block it gets. Something like

class Object
  def let(&block)
    yield self
  end
end

which enables the following silly example

"hello cruel world".split.let do |p|
  puts "The number of words in '#{p.join(' ')}' is #{p.length}"
  puts "and the second one is '#{p[1]}'"
  p
end

instead of

p = "hello cruel world".split
puts "The number of words in '#{p.join(' ')}' is #{p.length}"
puts "and the second one is '#{p[1]}'"

Well guess what? The upcoming Ruby 1.9 release a new ‘’tap’’ method is included that is similar, though not identical.