JavaScript-like HashMaps in Ruby

screenshot◎ Photo by Joshua Aragon on Unsplash

In the previous JavaScript like object in Ruby on Rails article, I’ve described how similar behavior can be achieved in Rails code.

But in pure Ruby there still is no short way for this.

It turns out that a proposal to Ruby core has been made to add this nice-to-have feature.

The idea is simple and elegant at the same time.

What if we add some “sugar” that runs the following code under the hood

person = Struct.new(:name, :country).new('Yukihiro', 'Japan')
# => #<struct  name="Yukihiro", country="Japan">
puts person.name
# => "Yukihiro"

And this is exactly what Koichi Sasada proposes in his PR.

The “sugar” syntax would be like this for the above example

person = ${name: 'Yukihiro', country: 'Japan'}
// => #<struct  name="Yukihiro", country="Japan">
puts person.name
// => "Yukihiro"

It makes it not only easier to write the .name instead of the additional three characters [:], but also helps when you make a typo like person.nama.

You’ll get an error raised

> person.nama
NoMethodError: undefined method `nama' for #<struct name="Yukihiro", country="Japan">
Did you mean?  name

instead of the silent nil with the Hash type

person = {name: 'Yukihiro'}
person[:nama]
# => nil

Let’s hope that this change will make it one way or another into the Ruby core 👍