If key does not exist create default value
Solution 1
If you already have a hash, you can do this:
h.fetch(key, "default value")
Or you exploit the fact that a non-existing key will return nil
:
h[key] || "default value"
To create hashes with default values it depends on what you want to do exactly.
-
Independent of key and will not be stored:
h = Hash.new("foo") h[1] #=> "foo" h #=> {}
-
Dependent on the key and will be stored:
h = Hash.new { |h, k| h[k] = k * k } h[2] #=> 4 h #=> {2=>4}
Solution 2
Constructor of Hash class accept a default value, same will be returned if a matching key is not found.
h = Hash.new("default")
h.has_key?("jake")
=> false
h["jake"]
=> "default"
h["jake"] = "26"
h.has_key?("jake")
=> true
Solution 3
If you don't need to store that default value into hash you can use Hash#fetch
method:
hash = {}
hash.fetch(:some_key, 'default-value') # => 'default-value'
p hash
# => {}
If you need in addition to store your default value every time you access non-existent key and you're the one initializing the hash you can do it using Hash#new
with a block:
hash = Hash.new { |hash, key| hash[key] = 'default-value' }
hash[:a] = 'foo'
p hash[:b]
# => 'default-value'
p hash
# => { :a => 'foo', :b => 'default-value' }
Solution 4
You can use the ||=
operator:
hash = {some_key: 'some_value'}
puts hash[:some_key] ||= 'default_value' # prints 'some_value'
puts hash[:non_existing_key] ||= 'default_value' # prints 'default_value'
puts hash.inspect # {:some_key=>"some_value", :non_existing_key=>"default_value"}
Solution 5
If you are storing a default value that might be nil and you need to calculate it at storage time:
hash = {}
...
hash.fetch(key) {|k| hash[k] = calc_default()}
Steve
Updated on August 03, 2022Comments
-
Steve almost 2 years
Can anyone show me a ruby way of checking if a key exists in a hash and if it does not then give it a default value. I'm assuming there is a one liner using unless to do this but I'm not sure what to use.
-
Sebastian about 12 yearsUsing h[key] || "default value" is not save, if there is already false in there it will be overridden
-
Michael Kohl about 12 yearsThat's why I listed it as one of several possibilities. Generally people do have an idea of what the values of their hashes are gonna be like, if you know you are not gonna save boolean values, it's a perfectly fine approach.