New Ruby programmers probably do something like this:
This works fine until some falsy values are introduced:
😩
When using || your falsy values will be overwritten. This is most probably not your intention. Instead of that use Hash#fetch.
Hash#fetch is best used when:
The default value for individual keys are calculated in a very different way
Values can be falsy
It’s also great to ensure a key is present
Don’t use it when:
You’d like the default values to be saved in the hash
You have a set of default values ( just merge your default into the hash )
Hash#fetch also has a second notation for the default value:
I only use the notation with a block. There are no real benefits to the other notation except maybe some performance difference in super simple cases. In most cases though, the block version will be the better choice. It will postpone the evaluation of the default value until it’s needed; and - at lest to me - it looks better. 😍