This is Fundbase Nerds, written by the team behind Fundbase.

Go to Fundbase  

New pintxos de Ruby

A few cool bits in the newest release

Posted by Marek Stanczyk on

I think it doesn’t come surprising that Ruby is my favorite language. By now it’s past its most radical changes, which happened from version 1.8 to 1.9 (and they were intentionally done without changing the major version number, in order not to scare people from upgrading). Since version 2.0, the language became much more mature, but versions 2.1 through 2.3 still deliver useful improvements. I’m going to briefly show you a few of them.

Safe navigation operator

I find the existential operator accessor in CoffeeScript very useful:

if user?.organization?.investor

This improvement was now added to Ruby, however with a different syntax, because the question mark is allowed as last character of a method name.

if user&.organization&.investor
# instead of
if user && user.organization && user.organization.investor

Much better than a chain of nil checks or an if pyramid.

Array#dig and Hash#dig

Ever needed to get a value from a nested array or hash? Something like

array[0][1][2] if array[0] && array[0][1]
hash[:first][:second][:third] if hash[:first] && hash[:first][:second]

Ouch. Now we can simply dig it:

array.dig(0, 1, 2)
hash.dig(:first, :second, :third)

Cleaner, isn’t it?


This one might not be needed every day (or every other day), but is still quite cool. An Enumerable can now be mapped through keys of a Hash:

prices = { apple: 1, banana: 2, celery: 3 }
%i[apple plum banana].map(&prices) # => [1, nil, 2]

Which leads me to one similar extension of my own:

Bonus: Array#to_proc

I’m sure you often do something like
# which is actually sugar for Symbol#to_proc { |item| item.some_method_or_field }

I often found myself in the need to map by a hash key instead, which is quite similar to the above, but I always had to write { |item| item[key] }

However, I was thinking, why couldn’t I make it shorter too? This would be nice:[key])

Luckily, Array#to_proc didn’t exist, so I added:

class Array
  def to_proc do |object|

And now I can map by a hash key or an array index, too!

Marek Stanczyk

Marek is a Fullstack developer at Fundbase.
Loves beautiful code and enjoys developing with Ruby and Rails the most.