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