Skip to main content


Showing posts from May, 2013

Ruby Idioms part 1

Ruby is like a language in that it has phrases that are used, and ones that work better than others. The most common rubyism is a ||= b where a is set to b if it is not nil, false or undefined. It basically means if a has a value move on but if it doesn't set it to b. Simple enough.

But an even more powerful one but less well known is the index feature one. Arrays, hashes and even more importantly strings have this function too.

In hashes it's the normal way to get a value by sending it its key. So:
hashy = {:key1 =>  :value1, :key2 => {:subkey1 => :subvalue1}}
will spit out
But it's really useful for strings too.

stringy = "Friends, Romans, countrymen, lend me your ears;"
stringy['lend me your ears'] #=> "lend me your ears"

You can also chain this calls which leads to some weird things.

stringy['lend me your ears'].upcase['EARS']   #=>  "EARS"

I just used a bit of this actual code o…