Ruby 1.9 散列,键中有破折号 [英] Ruby 1.9 hash with a dash in a key
本文介绍了Ruby 1.9 散列,键中有破折号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 ruby 1.9 中有没有办法用新的语法定义这个哈希?
In ruby 1.9 is there a way to define this hash with the new syntax?
irb> { a: 2 }
=> {:a=>2}
irb> { a-b: 2 }
SyntaxError: (irb):5: syntax error, unexpected tLABEL
{ a-b: 2 }
^
使用旧的,它可以工作:
with the old one, it's working:
irb> { :"a-b" => 2 }
=> {:"a-b"=>2}
推荐答案
从 Ruby 2.2 开始,您还可以使用以下语法:
As of Ruby 2.2, you also can use following syntax:
{a: 1, b: 2, 'c-c': 3, d: 4}
这篇关于Ruby 1.9 散列,键中有破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文