If key does not exist create default value

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}
    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)