Ruby/Rails hash rockets Syntax [closed]

江枫思渺然 提交于 2019-12-02 16:26:18

问题


Can someone point me to a good primer just explaining the different syntactic features in Ruby/Rails? For instance, how come some examples I see do myMethod(x: "z") and others do myMethod(:x => "x")?

The syntax in general seems strange to me, just looking for a quick at-a-glance reference to use as a cheat sheet.


回答1:


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?



来源:https://stackoverflow.com/questions/18835189/ruby-rails-hash-rockets-syntax

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