Main Content

Adding a member to a Hash in Ruby

Archive - Originally posted on "The Horse's Mouth" - 2006-12-16 04:49:00 - Graham Ellis

In Ruby, you must initialise your variables - in other words, you cannot use the content of a variable that doesn't exist and have the language assume it will be 0, as happened with Perl.

So if - for example - you're using a Hash to keep tabs of a number of counters, you can't just +=1 members and have them automatically created if the dont already exist - you get an exception:

irb(main):001:0> demo = {}
=> {}
irb(main):002:0> demo["Graham"] = 25
=> 25
irb(main):003:0> demo["Graham"] += 1
=> 26
irb(main):004:0> demo["Lisa"] += 1
NameError: undefined method `+' for nil
from (irb):4


The fetch method on a Hash allows you to fetch a value if one exists, but return a default if the element you're looking for is undefined and that's a really effective way of initialising new counters to 0:

irb(main):005:0> demo["Graham"] = demo.fetch("Graham",0) + 1
=> 27
irb(main):006:0> demo["Lisa"] = demo.fetch("Lisa",0) + 1
=> 1
irb(main):007:0>


In some circumstances, the fetch behaviour is what you'll want .... but in others, it's more likely to be better to process the circumstance via an exception with a rescue clause.