前结肠对后结肠

在使用 Ruby 时,我总是与 :混在一起。

有没有人能解释一下什么时候我应该在变量名之前使用它,比如 :name,什么时候我应该在变量名之后使用它,比如 name:

举个例子就够了。

40969 次浏览

You are welcome for both, while creating Hash :

{:name => "foo"}
#or
{name: 'foo'} # This is allowed since Ruby 1.9

But basically :name is a Symbol object in Ruby.

From docs

Hashes allow an alternate syntax form when your keys are always symbols. Instead of

options = { :font_size => 10, :font_family => "Arial" }

You could write it as:

options = { font_size: 10, font_family: "Arial" }

:name is a symbol. name: "Bob" is a special short-hand syntax for defining a Hash with the symbol :name a key and the string "Bob" as a value, which would otherwise be written as { :name => "Bob" }.

You can use it after when you are creating a hash.

You use it before when you are wanting to reference a symbol.

In Arup's example, {name: 'foo'} you are creating a symbol, and using it as a key.

Later, if that hash is stored in a variable baz, you can reference the created key as a symbol:

baz[:name]

This has absolutely nothing to do with variables.

:foo is a Symbol literal, just like 'foo' is a String literal and 42 is an Integer literal.

foo: is used in three places:

  • as an alternative syntax for Symbol literals as the key of a Hash literal: { foo: 42 } # the same as { :foo => 42 }
  • in a parameter list for declaring a keyword parameter: def foo(bar:) end
  • in an argument list for passing a keyword argument: foo(bar: 42)