ruby hash per-value defaults

Here’s a quick tip for assigning default values with a ruby hash. It’s well publicized that you can set an overall default (i think this is called “default assignment”) for the hash with the .default method like this (stolen directly from the rubydocs):

h = Hash.new                            #=> {}
   h.default                               #=> nil
   h.default(2)                            #=> nil

   h = Hash.new("cat")                     #=> {}
   h.default                               #=> "cat"
   h.default(2)                            #=> "cat"

   h = Hash.new {|h,k| h[k] = k.to_i*10}   #=> {}
   h.default                               #=> 0
   h.default(2)                            #=> 20</pre>

But you can also set per-key defaults using the or-operator. if an assigned value is false, or nil, you’ll get the default value. See below:

ruby-1.9.1-p378 > x = {}
=> value: {}
ruby-1.9.1-p378 > x[:y] = "y"
=> value: "y"
ruby-1.9.1-p378 > x[:y]
=> value: "y"
ruby-1.9.1-p378 > x[:y] = "y" || "noty"
=> value: "y"
ruby-1.9.1-p378 > x[:y]
=> value: "y"
ruby-1.9.1-p378 > x[:y] = nil || "noty"
=> value: "noty"
ruby-1.9.1-p378 > x[:y] = false || "noty"
=> value: "noty"
ruby-1.9.1-p378 > x[:y] = "" || "noty"
=> value: ""

… Note that or-assignment doesn’t work in this case:

ruby-1.9.1-p378 > x[:y] = "" ||= "noty"
SyntaxError: (irb):19: syntax error, unexpected tOP_ASGN, expecting $end
x[:y] = "" ||= "noty"
^
from /home/jcran/.rvm/rubies/ruby-1.9.1-p378/bin/irb:17:in `<main>'
ruby-1.9.1-p378 >

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s