Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

ruby - If key does not exist create default value

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.

question from:https://stackoverflow.com/questions/9108619/if-key-does-not-exist-create-default-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...