I'm ready to conclude about the Ruby 3.1 hash shorthand syntax.
The new syntax allows you to write more concise code where you pass-on local variables to methods or hashes.
@@ -1,3 +1,3 @@
def log_json(level:, message:)
- Logger.log({ level: level, message: message }.to_json)
+ Logger.log({ level:, message: }.to_json)
end
I think this is useful, but only in rare cases, for example if there is a lot of redirection.
But there is one really big issue with the new syntax:
rubocop choose the wrong default (EnforcedShorthandSyntax: always
).
The following reasoning would speak for the much better default setting EnforcedShorthandSyntax: either
.
1. It's hard to spot
For example try to distinguish between the following two statements which mean something completely different.
expect(RealtySnapshot.all).to all(have_attributes(realty:))
expect(RealtySnapshot.all).to all(have_attributes(:realty))
2. It's not good prose
build(:realty, address:)
It indicates to my mind that address
is empty. My mind replaces the non-existent anything after the colon with nil
.
3. Maintaining consistency is cumbersome.
Assume you call a FactoryBot factory like this:
build(:realty, address:)
As soon as you add another parameter you'll need to change the whole parameter list to be consistent.
build(:realty, address: address, active: true)
Conclusion
I see that the hash shorthand syntax should bring us some joy over from the JavaScript world, but I don't think this went well. The shorthands just works better in JavaScript because the role of the colon is much more limited.
Top comments (0)