Alex Rivera | Logout

If key does not exist create default value

Asked 2012-02-02T07:31:43.467
52

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.

Edit
Report

1 Answer

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()}
answered 2012-12-09T14:50:35.330

Your Answer