Ruby 1.9 中新的哈希语法有什么好处? [英] What are the benefits of the new hash syntax in Ruby 1.9?

查看:40
本文介绍了Ruby 1.9 中新的哈希语法有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了使以符号为键的散列定义更简洁外,将散列编写为:

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"} 而不是 {:key1 =>"value1", :key2 =>"value2"}?

此外,当您将字符串和符号混合用作哈希键时,有什么约定?

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

你把它写成 {"key1" =>"value1", key2: "value2"} 或保持样式一致 {"key1" =>"value1", :key =>"value2"}

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

推荐答案

它只是看起来更好——它的语法糖;最终结果是一样的.

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.

对于符号值,我还对整个哈希使用旧的 hash-rocket 语法–这看起来很糟糕:

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

{ 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.

这篇关于Ruby 1.9 中新的哈希语法有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆