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

Keep your ~/.bash_history entries unique

When often using the terminal you don’t want to type certain commands over and over again. Although recent commands are stored in the .bash_history in your home-directory they will be overwritten at some point when a new terminal is opened. So you won’t be able to use Ctrl + R to search for commands you’ve typed longer time ago. Luckily there is an option to append the terminal commands instead of overwriting them.