Doug's Compendium of Stuff


Stuff

Main
Where Is Doug?
My Bookmarks
My Resume
Pacbell Outages
Pilot Logbook

Code

Tournament
Jar Search
DCT6200 Firewire Tuner (For Motorola DCT6200 set top box and Freevo)
Serial Port Tuner (For Motorola DCT2XXX set top box and Freevo)
Gentoo IVTV Ebuild
Java Internet Jukebox

Old

2009: 12 11 10 09 08
2008: 12 09 08 07 03 02
2007: 12 08 07
2006: 12 06 02
2005: 11 10 07 06 05 04
2004: 07 06
2003: 10 08 07 05 04

Offsite

My Wife
My Trainer
My Work

Contact

Email:



The Few, The Proud, The Pradipta 416


Why I Like Ruby

08/25/2009

This example shows the thing I like about the Ruby language the most. It is simple but opens up subtle possibilities and works in a way that you don't have to think about. It works exactly as you would expect it to work. It could have worked the other way and Ruby would have suffered for it.

class Foo
  def m
    puts 'before yield'
    yield
    puts 'after yield'
  end

  def f
    puts 'calling m'
    m { puts 'in block'; return 'stuff'}
    puts 'done calling m'
  end
end

foo = Foo.new
r = foo.f

puts "method f returned: #{r}"

Running this program yields the following output:

$ ruby example.rb
calling m
before yield
in block
method f returned: stuff

When calling m and passing a block with a return statement, the return is done from the calling method f. Neither the 'after yield' nor the 'done calling m' statement is executed. This is exactly as it should work, but I can imagine other implementations where one or both of these statements were called. It wouldn't have been as beautiful, however.

As my wife is fond of saying, "It's the little things ..." Thanks, Matz.

Locations of visitors to this page