Skip to content

Instantly share code, notes, and snippets.

@Frost
Created January 8, 2014 10:06
Show Gist options
  • Select an option

  • Save Frost/8314485 to your computer and use it in GitHub Desktop.

Select an option

Save Frost/8314485 to your computer and use it in GitHub Desktop.
Default values for hashes in ruby
# So... hash.new takes an optional parameter with a default value, that's neat.
> hash = Hash.new(0)
> hash["foo"]
=> 0
> hash["bar"] += 5
=> 5
> hash
=> {"bar" => 5}
# Cool, let's try something a bit more interesting
> hash = Hash.new([])
> hash = Hash.new []
=> {}
> hash
=> {}
> hash["foo"]
=> []
> hash["bar"] << 17
=> [17]
> hash
=> {}
> hash["foo"]
=> [17]
# Eh, what? That seems a bit odd.
# It turns out that providing Hash.new with an array and then calling << for any non-existent value of that hash, actually modifies the default value.
# That can be solved by providing a block to Hash.new, like so:
> hash = Hash.new {|hsh, key| hsh[key] = [] }
=> {}
> hash["foo"]
=> []
> hash
=> {"foo"=>[]}
> hash["bar"] << 17
=> [17]
> hash
=> {"foo"=>[], "bar"=>[17]}
# This, however, has the side-effect that even asking for a key will create it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment