在Ruby 1.9中新的哈希语法有什么好处?

时间:2022-06-05 00:37:35

Apart from making it sightly more concise for defining hashes with symbols as keys, are there any other benefits of writing a hash as:

除了让哈希更简洁地定义以符号作为键的哈希之外,将哈希写为:

{key1: "value1", key2: "value2"} instead of {:key1 => "value1", :key2 => "value2"}?

{key1: "value1", key2: "value2"}而不是{:key1 => "value1",:key2 => "value2"}?

Also, what is the convention when you have a mix of strings and symbols as hash keys?

还有,当字符串和符号作为哈希键混合时,惯例是什么?

Do you write it as {"key1" => "value1", key2: "value2"} or keep the style consistant as {"key1" => "value1", :key => "value2"}

您是否将其写成{“key1”=>“value1”,key2:“value2”},还是将样式设置为{“key1”=>“value1”,:key =>“value2”}

2 个解决方案

#1


11  

It just looks nicer--it's syntactic sugar; it ends up being the same thing.

看起来不错,是语法糖;结果是一样的。

When mixing keys (ew, why would you do that?) I use the old hash-rocket syntax for the entire hash.

当混合键(ew,为什么要这样做?)我对整个散列使用旧的哈希-rocket语法。

With symbol values I also use the old hash-rocket syntax for the entire hash–this looks icky:

对于符号值,我还在整个hashrocket语法中使用了旧的语法—这看起来很恶心:

{ ohai: :kthxbye }

I don't like mixing the two styles in the same hash–I think it's confusing.

我不喜欢把这两种风格混在一个话题里——我觉得这让人困惑。

This is all based on personal preference, though.

这都是基于个人喜好。

#2


3  

It's shorter, and similar to JavaScript notation. Not worth to migrate old notation to the new for any reason, but otherwise choose which you like.

它更短,类似于JavaScript符号。不值得因为任何原因将旧的表示法迁移到新的表示法中,但是可以选择您喜欢的。

Always keep the code consistent, don't mix notations. It's more readable that way.

始终保持代码一致,不要混合符号。这样更易读。

#1


11  

It just looks nicer--it's syntactic sugar; it ends up being the same thing.

看起来不错,是语法糖;结果是一样的。

When mixing keys (ew, why would you do that?) I use the old hash-rocket syntax for the entire hash.

当混合键(ew,为什么要这样做?)我对整个散列使用旧的哈希-rocket语法。

With symbol values I also use the old hash-rocket syntax for the entire hash–this looks icky:

对于符号值,我还在整个hashrocket语法中使用了旧的语法—这看起来很恶心:

{ ohai: :kthxbye }

I don't like mixing the two styles in the same hash–I think it's confusing.

我不喜欢把这两种风格混在一个话题里——我觉得这让人困惑。

This is all based on personal preference, though.

这都是基于个人喜好。

#2


3  

It's shorter, and similar to JavaScript notation. Not worth to migrate old notation to the new for any reason, but otherwise choose which you like.

它更短,类似于JavaScript符号。不值得因为任何原因将旧的表示法迁移到新的表示法中,但是可以选择您喜欢的。

Always keep the code consistent, don't mix notations. It's more readable that way.

始终保持代码一致,不要混合符号。这样更易读。