问题描述
可能的重复:
map(&:name) 在 Ruby 中是什么意思?
survey.map(&:questions).flatten.compact
之类的东西是什么,所以我可以找到有关它们的更多信息:).&:
解决了什么问题,或者它到底在做什么?是否用于其他语言?
What are things like survey.map(&:questions).flatten.compact
called, so I can find more information about them :). What problems does that &:
solve, or what is it doing exactly? Is it used in other languages?
推荐答案
This is shorthand for:
This is shorthand for:
survey.map { |s| s.questions }.flatten.compact
这是Symbol#to_proc
方法.它曾经是 Rails 的 ActiveSupport 的一部分,但后来被添加到 Ruby 语法中.
It's the Symbol#to_proc
method. It used to be a part of Rails' ActiveSupport, but has since been added to Ruby syntax.
就性能而言,我编写了一个快速的基准测试脚本来了解 1.8 和 1.9 中的性能效果.
As far as performance goes, I wrote a quick benchmark script to get an idea of performance effect in both 1.8 and 1.9.
require 'benchmark'
many = 500
a = (1..10000).to_a
Benchmark.bm do |x|
x.report('block once') { a.map { |n| n.to_s } }
x.report('to_proc once') { a.map(&:to_s) }
x.report('block many') { many.times { a.map { |n| n.to_s } } }
x.report('to_proc many') { many.times { a.map(&:to_s) } }
end
首先,在给你结果之前 - 如果你还不确定 Ruby 1.9 总体上是一个巨大的速度改进,准备被吹走.
First off, before giving you the results - if you weren't already sure that Ruby 1.9 was a huge speed improvement in general, prepare to be blown away.
user system total real
block once 0.020000 0.000000 0.020000 ( 0.016781)
to_proc once 0.010000 0.000000 0.010000 ( 0.013881)
block many 6.680000 1.100000 7.780000 ( 7.780532)
to_proc many 7.370000 0.540000 7.910000 ( 7.902935)
Ruby 1.9 结果:
user system total real
block once 0.010000 0.000000 0.010000 ( 0.011433)
to_proc once 0.000000 0.000000 0.000000 ( 0.004929)
block many 4.060000 0.000000 4.060000 ( 4.057013)
to_proc many 2.810000 0.000000 2.810000 ( 2.810312)
首先:哇.Ruby 1.9 很快.但我们在这里得出的更相关的结论很有趣:
First off: Wow. Ruby 1.9 is fast. But the more relevant conclusions we draw here are interesting:
- 在这两种情况下,仅运行一次,
to_proc
显然更快.在多次运行的 1.8 中,它有点慢.这似乎表明唯一真正的性能瓶颈是创建所有这些 Proc 对象. - 然而,在 Ruby 1.9 中,
to_proc
方法显然比块快得多,无论您执行多少次.在这种情况下,您不仅可以获得更简洁的代码,还可以提高性能.
- In both cases, for only one run,
to_proc
is clearly faster. In 1.8 on the many-times run, it's tad slower. This seems to indicate that the only real performance bottleneck is creating all those Proc objects. - In Ruby 1.9, however, the
to_proc
method is clearly much faster than blocks, no matter how many times you do it. In this case, you not only get cleaner code, but improved performance, as well.
最后,无论您使用哪个版本,to_proc
显然都不足以成为值得不使用的性能问题 - 事实上,它有时会加快速度!
In the end, no matter which version you're using, to_proc
is clearly not enough of a performance issue to be worth not using - in fact, it sometimes speeds things up!
这篇关于这个 &:last Ruby 构造叫什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!