Jesús Gabriel y Galán
3/25/2008 12:51:00 PM
On Tue, Mar 25, 2008 at 1:41 PM, Adam Akhtar <adamtemporary@gmail.com> wrote:
>
> > The most common idiom is:
> >
> > (hash[key] ||= []) << value
> >
>
> Thanks for the reply. Can I ask what these || mean..in this case do they
> mean OR???
a ||= b means a = a || b
and it's a common idiom to assign a value only when the lhs is nil (or false).
A hash by default will return nil for non-existing keys so:
hash[key] ||= [] could be written as hash[key] = hash[key] || []
and means: if the key is not present in the hash, create that entry in
the hash with an empty array as the value.
> does anyone have any good links on using the use of arrays with hashes
> in this manner?
I don't have a link, but if you are doing that in a lot of places, remember you
can change the default behaviour of a hash to do the above for you:
hash = Hash.new {|h,k| h[k] = []}
from there on you can say just:
hash[key] << value
because the default value for an inexistent key will trigger the
creation of a new array assigned to that key.
Jesus.