Ruby/Rails hash rockets Syntax [closed]

こ雲淡風輕ζ 提交于 2019-12-02 09:36:36
MrYoshiji

They are the same, it is just a matter of preferences.

I also asked myself why would we add this new syntax if we already have one? Well, Programming with Ruby implies that we are lazy and want to type the less possible caracters. So this new syntax allow us - lazy programmers - to write the same thing, minus 1 caracter!


But keep in mind some stuff, like the type of the keys for instance (Ruby 1.9.3):

> {a: 12}.class
 => Hash 
> {:a => 12}.class
 => Hash 
> {'a' => 12}.keys.first.class
 => String 
> {a: 12}.keys.first.class
 => Symbol

Also, some declaration are illegal with the new syntax:

> { '1-2' => "something" }
 => {"1-2"=>"something"} 
> { 1-2: "something" }
SyntaxError: (irb):38: syntax error, unexpected ':', expecting tASSOC
{ 1-2: "something" }
      ^
(irb):38: syntax error, unexpected '}', expecting $end

For more informations: Is there any difference between the `:key => "value"` and `key: "value"` hash notations?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!