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}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…