Hash#transform_keys

Ruby 2.5 introduced several new methods. Everyone is happy for yield_self (don’t get my wrong, me too), but I’m very excited for one I’ve been waiting for: Hash#transform_keys. It does exactly what it name implies, it provides a way to transform each key on the Hash. What’s the use for this? well, let’s explore one…

Read More

Hash#dig

Has this ever happened to you? You have a json structure that gets converted into a hash. It has a structure that’s a variation on this: { ‘product’: { ‘title’: ‘Light saber’, ‘type’: ‘weapon’, ‘price’: { ‘value’: 1000, ‘currency’: ‘Imperial credits’ } } } Say we want to extract the value attribute from the last…

Read More

Using case statements vs. using a Hash for simple selections in Ruby

The other day I found this piece of code at work: case status when 'booked' MyNamespace::Success when 'cancelled', 'canceled' MyNamespace::Cancelled when 'pending' MyNamespace::Pending else MyNamespace::Unknown end and I remembered that in one of her talks, Sandi Metz used a Ruby Hash to select a class for a factory. Something like this: { 'booked' => MyNamespace::Success,…

Read More