Ruby 中的冒号运算符是什么?

发布于 2024-11-15 01:31:51 字数 137 浏览 1 评论 0原文

当我说 { :bla =>; 1、:bloop => 2 }: 到底是做什么的?我在某处读到它与字符串相似,但在某种程度上是一个符号。

我对这个概念不是很清楚,有人可以启发我吗?

When I say { :bla => 1, :bloop => 2 }, what exactly does the : do? I read somewhere about how it's similar to a string, but somehow a symbol.

I'm not super-clear on the concept, could someone enlighten me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

北方的巷 2024-11-22 01:31:51

:foo 是一个名为“foo”的符号。符号具有一个独特的特征,即任何两个名称相同的符号都将是相同的:

"foo".equal? "foo"  # false
:foo.equal? :foo    # true

这使得比较两个符号非常快(因为只涉及指针比较,而不是像字符串中那样比较所有字符),而且您还赢了不会有无数相同符号的副本漂浮在周围。

此外,与字符串不同,符号是不可变的。

:foo is a symbol named "foo". Symbols have the distinct feature that any two symbols named the same will be identical:

"foo".equal? "foo"  # false
:foo.equal? :foo    # true

This makes comparing two symbols really fast (since only a pointer comparison is involved, as opposed to comparing all the characters like you would in a string), plus you won't have a zillion copies of the same symbol floating about.

Also, unlike strings, symbols are immutable.

夏了南城 2024-11-22 01:31:51

只是为了演示答案中提到的一些内容:

require 'benchmark'

n = 1_000_000

print '"foo".equal? "foo" -> ', ("foo".equal? "foo"), "\n"
print '"foo" == "foo"     -> ', ("foo" == "foo"    ), "\n"
print ':foo.equal? :foo   -> ', (:foo.equal? :foo  ), "\n"
print ':foo == :foo       -> ', (:foo == :foo      ), "\n"

Benchmark.bm(10) do |b|
  b.report('string')     { n.times { "foo".equal? "foo" }}
  b.report('str == str') { n.times { "foo" == "foo"     }}
  b.report('symbol')     { n.times { :foo.equal? :foo   }}
  b.report('sym == sym') { n.times { :foo == :foo       }}
end

运行它输出:

"foo".equal? "foo" -> false
"foo" == "foo"     -> true
:foo.equal? :foo   -> true
:foo == :foo       -> true

因此,使用 equal? 比较字符串与字符串会失败,因为它们是不同的对象,即使它们内容相同。 == 比较内容,用符号进行等效检查要快得多。

                 user     system      total        real
string       0.370000   0.000000   0.370000 (  0.371700)
str == str   0.330000   0.000000   0.330000 (  0.326368)
symbol       0.170000   0.000000   0.170000 (  0.174641)
sym == sym   0.180000   0.000000   0.180000 (  0.179374)

就速度而言,两种符号测试基本相同。经过 1,000,000 次迭代后,只有 0.004733 秒的差异,所以我想说这是使用的一次清洗。

Just to demonstrate some of the things mentioned in the answers:

require 'benchmark'

n = 1_000_000

print '"foo".equal? "foo" -> ', ("foo".equal? "foo"), "\n"
print '"foo" == "foo"     -> ', ("foo" == "foo"    ), "\n"
print ':foo.equal? :foo   -> ', (:foo.equal? :foo  ), "\n"
print ':foo == :foo       -> ', (:foo == :foo      ), "\n"

Benchmark.bm(10) do |b|
  b.report('string')     { n.times { "foo".equal? "foo" }}
  b.report('str == str') { n.times { "foo" == "foo"     }}
  b.report('symbol')     { n.times { :foo.equal? :foo   }}
  b.report('sym == sym') { n.times { :foo == :foo       }}
end

Running it outputs:

"foo".equal? "foo" -> false
"foo" == "foo"     -> true
:foo.equal? :foo   -> true
:foo == :foo       -> true

So, comparing a string to a string using equal? fails because they're different objects, even if they are equal content. == compares the content, and the equivalent checks with symbols are much faster.

                 user     system      total        real
string       0.370000   0.000000   0.370000 (  0.371700)
str == str   0.330000   0.000000   0.330000 (  0.326368)
symbol       0.170000   0.000000   0.170000 (  0.174641)
sym == sym   0.180000   0.000000   0.180000 (  0.179374)

Both symbol tests are basically the same as far as speed. After 1,000,000 iterations there's only 0.004733 second difference, so I'd say it's a wash between which to use.

嘦怹 2024-11-22 01:31:51

符号是 ruby​​ 中表示字符串和名称的一种方式。

符号和字符串之间的主要区别在于,同名符号在 ruby​​ 会话期间仅被初始化并在内存中仅存在一次。

当您需要使用相同的单词来表示不同的事物时,它们非常有用

Symbols are a way to represent strings and names in ruby.

The main difference between symbols and strings is that symbols of the same name are initialized and exist in memory only once during a session of ruby.

They are useful when you need to use the same word to represent different things

爱,才寂寞 2024-11-22 01:31:51

有一些引自名著Agile Web Development with Rails的内容,可能也有助于理解符号

Rails 使用符号来识别事物。特别是,在命名方法参数和在哈希中查找内容时,它使用它们作为键。

redirect_to :action => "edit", :id => params[:id]

您可以将符号视为字符串文字,它们被神奇地制成常量。或者,您可以将冒号视为“名为的事物”,因此 :id 是“名为 id 的事物”。

There're some quotes from the famous book Agile Web Development with Rails, which may be helpful to understand the symbol as well :

Rails uses symbols to identify things. In particular, it uses them as keys when naming method parameters and looking things up in hashes.

redirect_to :action => "edit", :id => params[:id]

You can think of symbols as string literals that are magically made into constants. Alternatively, you can consider the colon to mean "the thing named", so :id is "the thing named id".

许久 2024-11-22 01:31:51

在 ruby​​ 中,每个对象都有一个唯一的对象标识符,如果您在 irb 中写入 puts "hello".object_id 并按回车键 2 次不同的时间,您将获得 2 个不同的返回值,但是如果您写入 < code>:hello.object_id 2次你只会得到相同的返回值。
这应该可以解释其中的差异。

In ruby each object has a unique object identifier, if you write puts "hello".object_id in your irb and hit return for 2 different times, you will get 2 different returning value,but if you write :hello.object_id 2 times you will only get the same one returning value.
That should have explained the difference.

不喜欢何必死缠烂打 2024-11-22 01:31:51

如果您使用 :foo =>; bar, foo 将是一个符号。符号的好处是它们是独一无二的。当您调用哈希中的某个项目时,您会执行hash[:foo]

符号比字符串需要更少的内存,如果你想让你的程序更快一点,这也使得它们很有用。

If you use :foo => bar, foo will be a symbol. The benefit to symbols is that they are unique. When you call on an item in the hash, you do hash[:foo].

Symbols require less memory than strings, which also makes them useful if you want to make your program a little faster.

离旧人 2024-11-22 01:31:51

所有这些答案都忽略了一个额外的诱人细节..如果你将符号 :foo 字符串化,你会得到..猜猜看..字符串“foo”。因此

irb(main):025:0>
irb(main):026:0> :foo
=> :foo
irb(main):027:0> "#{:foo}"
=> "foo"
irb(main):028:0>
irb(main):029:0> 'foo' <=> :foo
=> nil
irb(main):030:0> 'foo' <=> :foo.to_s
=> 0
irb(main):031:0>

,对于 Perl 程序员来说,这是 Ruby 对“裸词”的回答。

All these answers omit one extra tantalising detail.. if you stringify the symbol :foo, you get.. guess what.. the string "foo". Hence

irb(main):025:0>
irb(main):026:0> :foo
=> :foo
irb(main):027:0> "#{:foo}"
=> "foo"
irb(main):028:0>
irb(main):029:0> 'foo' <=> :foo
=> nil
irb(main):030:0> 'foo' <=> :foo.to_s
=> 0
irb(main):031:0>

Hence.. for Perl programmers.. it's Ruby's answer to the 'bare word'.

弥枳 2024-11-22 01:31:51

这是一个象征。基本上,您是说散列的两个元素具有键 blabloop,就像您使用了字符串 "bla"和“bloop”。然而,它们比字符串占用更少的内存并且更容易输入。

It's a symbol. Basically, you are saying that the two elements of the hash have keys bla and bloop, much as if you had used the strings "bla" and "bloop". However, they take up less memory than strings and are easier to type.

苏璃陌 2024-11-22 01:31:51

如果您熟悉 Java,您可能会知道 Java 中的字符串是不可变的。 Ruby 中的符号在这个意义上是相似的。它们是不可变的,即,特定符号 :symbol 出现任意次数都将仅映射到单个内存地址。因此,建议尽可能使用符号,因为它可以优化内存使用。

If you are familiar with Java, you might be aware that Strings in Java are immutable. Symbols are similar in that sense in Ruby. They are immutable, i.e., any number of occurances of a particular symbol :symbol will map to only a single memory address. And, hence, it is recommended to use symbols wherever possible since it optimizes memory usage.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文