ruby - If key does not exist create default value

ID : 131365

viewed : 11

Tags : rubyhashruby

Top 5 Answer for ruby - If key does not exist create default value

vote vote

100

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} 
vote vote

80

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 
vote vote

79

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' } 
vote vote

64

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"} 
vote vote

60

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()} 

Top 3 video Explaining ruby - If key does not exist create default value

Related QUESTION?