3

Ruby 3.1 allows value omission in hash literals

 2 years ago
source link: https://blog.saeloun.com/2021/09/28/ruby-allow-value-omission-in-hash-literals
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Ruby 3.1 allows value omission in hash literals

Sep 28, 2021 , by Akhil G Krishnan 1 minute read

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};
console.log(c);

//=> {"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.

Before

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.

After

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK