As the keyword discussion keeps going on and enflaming passions, there is a Ruby proposed feature I’ve been wanting to talk about for a long time: shorthand hash syntax.
You see, very often in code, I will take care to name my variable and methods well, and structure the whole thing clearly. The consequence of that structure is that I will very often end up with structures such as:[^2]
{
topics: topics,
users: users,
very_longly_named_objects: very_longly_named_objects,
even_more_very_longly_named_objects: even_more_very_longly_named_objects,
}
It makes a lot of sense when you think about it: the hash will often be a collection of named things, and if one name makes sense, it will often reflect the one you already used in your code.
However, it’s quite long and tedious to type.
It’s a thing I never noticed before Javascript introduced the feature of typing that same object as:
{topics, users, very_longly_named_objects}
In other words, when no value is given, it will convert into {variable_name: variable_name}
And now, whenever I’m typing in Ruby, the most beautiful programming language that exists*, I’m greenly jealous of Javascript.[^1]
It’s one of those patterns that now I know they could exist, I am bothered every time I’m not using them cause they’re so great. (It is one of two such patterns I know of )
It has been proposed in Ruby (core)#15236. Alas, it was closed as of July 2019.
I’d like to open the discussion up about it here, seeing there is a good base of Ruby users, and this platform lends well to community discussion.
In my opinion, this proposed syntax feature:
- targets a pattern that is frequently used in a lot of Ruby code, Rails and non-Rails
- saves a considerable amount of code when used
- rewards good, descriptive variable/method naming
- is concise, readable, clear, elegant, in harmony with the spirit of Ruby, namely beautiful code that optimizes for programmer happiness
That is why we should support the spec.
*: Source: myself.
[^1]: Ruby, being jealous of Javascript. Can you imagine?
[^2]: And please keep in mind that these are example names only, yes if that were reality there would be a way to better structure this code. This does not make the general idea moot.—Sadly this is a point some people raise in debate.