The strangest thing in Ruby

gitguudd

Aaron Cheng

Posted on March 16, 2022

The strangest thing in Ruby

I recently ran in the the following error via Rubocop in Ruby 3.1:

Omit the hash value

I was puzzled and Googling didn't really help me find anything - until I dug into Rubocop itself (the error is given here)

It turns out that this warning is saying that we are now allowed to omit hash values if the variable name is the same as the hash key.

See the following example:

# Assume Point has two parameters, X and Y

# Before Ruby 3.1
x = 3
y = 10
Point.new(x: x, y: y)

# After Ruby 3.1
x = 3
y = 10
Point.new(x:, y:)
Enter fullscreen mode Exit fullscreen mode

Notice how we can now just use the key names and leave the variables empty!

It's called Ruby's hash omission syntax, and it's new, as of Ruby 3.1!

💖 💪 🙅 🚩
gitguudd
Aaron Cheng

Posted on March 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related