8ball-media

little pieces from everything

Some Ruby Idioms

A post as a note to myself to remember some Ruby Idioms ..

 # $ruby 1.9.2
 #
 # Add a value to an array unless its not
 # contained already and even it's contained
 # multiple times reduce it to a single occurence.

 foo  = ['bar', 'baz', 'baz']    # =>  ["bar", "baz", "baz"]
 foo |= ['baz']                  # =>  ["bar", "baz"]

 # Parallel assignment by "un-splatting" an result array
 # Instead of:
 match = "Ruby 1.9.2 is awesome".match(/Ruby (d.+) is awesome/)
 catch = match[1]

 # Use:
 catch, match = *"Ruby 1.9.2 is awesome".match(/Ruby (d.+) is awesome/)

 # catch => "Ruby 1.9.2 is awesome"
 # match => "1.9.2"

more to come..