I was looking at some ruby code I wrote a few days ago and something didn’t sit right with me. I had a bit of a code smell when setting a default value for a hash key if the key didn’t exist.
The scenario… there is a hash that has a search key which holds information for a search term, optionally the order key may be set also.
1
| |
Initially when the order key had not been set I would perform a check to see if they key existed then using the ternary operator set a default value. I think it looks a bit ugly though!
1
| |
How have I not heard of the fetch method before? Fetch takes a key argument which will be used to look up the key in the hash, optionally it takes a second parameter which is the value to return if the key has not been set.
1
| |
A small refactor which I think looks much nicer. This may be obvious to some, but it was one of those methods I had just never used!