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..

This entry was posted in ruby and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>