ES6 style hash literals in Ruby

(Or how to create a naughty fork of Ruby on your own machine)

I've been writing a lot of JavaScript code lately, and one pattern I see used a lot is something that I think is called an Object Literal.

The idea behind this syntax is that you frequently create hashes (or objects in JavaScript) that have a key that is the same name as the variable. i.e.

// some_old_skool_javascript_file.js
var name = "Chris";
var job_title = "Banana fan";
var user = {
  name: name,
  job_title: job_title

This can get tiresome - so the new Object Literal syntax lets you do the following:

// some_cool_new_javascript_file.js
let name = "Chris"
let job_title = "Banana fan";
let user = { name, job_title }

....and reader, I have been using this a LOT. Practically a good chunk of Vue.js is designed to be used like this.

And you know what - this is the sort of thing I would loved in Ruby! So I did some prying, and sure enough, Shugo Maeda had created a patch for this very syntax back in 2015.
(Check it out here)

This is what Matz had to say about it:

Well, until Matz changes his mind, you can throw caution to the wind and install this patch in your very own Ruby!

This patch is a little old now - but I created an updated patch here: - I literally added 3 characters, and it works with Ruby 2.5.0 - so hooray!

How to install

Well, I don't know how the cool kids install patches these days, but I found the easiest way for me was to use rvm. rvm lets you install patched versions of Ruby very easily. Here's how:

  1. First download the patch to your machine

  2. Use rvm to install the patch like this:

rvm install 2.5.0 -n imphash --patch imphash.patch

What the -n argument does is give this version of Ruby a name. The --patch argument lets you choose the patch file.

Now you can use this version of Ruby when you want to do cool stuff like this. Well done reader - you've got your very own version of Ruby!

# cool_new_ruby_file.rb
name = "Chris"
banana_appreciation = "high"
attrs = { name, banana_appreciation }
#=> {
  name: name,
  banana_appreciation: banana_appreciation

Wait - what's imphash mean?

Imphash is short for "implicit hash" - and because I don't know what this syntax is called I thought that imphash could be as good a name as any.

Feels a little...naughty and impish.

Subscribe via RSS

Back to all blog posts