Ruby:冒号之前与之后

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24661857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:32:04  来源:igfitidea点击:

Ruby: colon before vs after

ruby

提问by FloatingRock

When using Ruby, I keep getting mixed up with the :.

使用 Ruby 时,我总是与:.

Can someone please explain when I'm supposed to use it before the variable name, like :name, and when I'm supposed to use it after the variable like name:?

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

An example would be sublime.

一个例子是崇高的。

采纳答案by Arup Rakshit

You are welcome for both, while creating Hash:

欢迎您在创建时同时使用Hash

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

But basically :nameis a Symbolobject in Ruby.

但基本上:nameSymbolRuby中的一个对象。

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" }

回答by J?rg W Mittag

This has absolutely nothing to do with variables.

这与变量完全无关。

:foois a Symbolliteral, just like 'foo'is a Stringliteral and 42is an Integerliteral.

:fooSymbol文字,就像'foo'是一个String直译和42Integer文字。

foo:is used in three places:

foo:用在三个地方:

  • as an alternative syntax for Symbolliterals as the key of a Hashliteral: { 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)
  • 作为Symbol文字的替代语法作为文字的键Hash{ foo: 42 } # the same as { :foo => 42 }
  • 在用于声明关键字参数的参数列表中: def foo(bar:) end
  • 在用于传递关键字参数的参数列表中: foo(bar: 42)

回答by Chuck

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

:name是一个符号。name: "Bob"是一种特殊的简写语法,用于定义一个符号:name为键、字符串"Bob"为值的哈希,否则将写为{ :name => "Bob" }.

回答by vgoff

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.

在 Arup 的示例中,{name: 'foo'}您正在创建一个符号,并将其用作键。

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

稍后,如果该散列存储在变量 baz 中,您可以将创建的键作为符号引用:

baz[:name]

baz[:name]