Ruby 3.1 allows value omission in hash literals

Ruby 3.1 adds a shorthand syntax in Hash literals. It is similar to the shorthand syntax of objects in ECMAScript6.

Let us check the below example to see how the value omission on hash literals works in ECMAScript6.

const a = 1;
const b = 2;
const c = {a, b};

//=> {"a":1,"b":2}

The main advantage of this shorthand syntax is, if we want to define a hash whose keys have the same name as the variables passed in as properties, we can use the shorthand by passing the key name.


a = 1
b = 2
c = {a: a, b: b}
#=> {:a=>1, :b=>2}

c = {"a": a, "b": b}
#=> {:a=>1, :b=>2}

In the above example, we have to mention the value of each key in the hash, even if they have the same name.


a = 1
b = 2
c = {a:, b:}
#=> {:a=>1, :b=>2}

c = {"a":, "b":}
#=> Raises SyntaxError

In the above example, we have not added the values to hashes, only mentioned the keys. It will identify the value, having the same key name.

But here we can see that, if we specify keys as strings, it will raise an error.