Hidden features of Ruby

squadette picture squadette · Sep 15, 2008 · Viewed 41.9k times · Source

Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.

Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.

See also:

(Please, just one hidden feature per answer.)

Thank you

Answer

Farrel picture Farrel · Sep 15, 2008

From Ruby 1.9 Proc#=== is an alias to Proc#call, which means Proc objects can be used in case statements like so:

def multiple_of(factor)
  Proc.new{|product| product.modulo(factor).zero?}
end

case number
  when multiple_of(3)
    puts "Multiple of 3"
  when multiple_of(7)
    puts "Multiple of 7"
end