问题
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