为什么要在Ruby的某个属性上使用一元运算符?即& ;:第一 [英] Why would one use the unary operator on a property in ruby? i.e &:first
问题描述
Possible Duplicate:
Ruby/Ruby on Rails ampersand colon shortcut
作为一种习惯,我尝试定期阅读一些别人的源代码,并根据要点对它进行评论.现在,我正在阅读sinatra的基本应用程序,并遇到了一些有趣的代码(这是他们的Request类的一部分)
As a habit I try and read a little of someone elses source code regularly and comment on it in a gist. Right now I'm reading through sinatra's base app and came upon an interesting bit of code (this is part of their Request class)
def accept
@env['sinatra.accept'] ||= begin
entries = @env['HTTP_ACCEPT'].to_s.split(',')
entries.map { |e| accept_entry(e) }.sort_by(&:last).map(&:first)
end
end
我不了解的部分是&:last和&:first做的是什么?!?看起来很疯狂!
The part I don't get is what is &:last and &:first doing?!? It appears as madness!
推荐答案
阅读重复问题中有关&:...
含义和用法的答案.在这种情况下,entries
是一个数组,并且链接了三个方法map
,sort_by
和map
. sort_by(&:last)
等同于sort_by{|x| x.last}
. map(&:first)
与map{|x| x.first}
相同.第一个map
不使用&:...
的原因是因为(i)accept_entry
的接收者不是e
,并且(ii)接受了参数e
.
Read the answers in the duplicate questions for the meaning and usage of &:...
. In this case, entries
is an array, and there are three methods map
, sort_by
, and map
chained. sort_by(&:last)
is equivalent to sort_by{|x| x.last}
. map(&:first)
is the same as map{|x| x.first}
. The reason the first map
does not use &:...
is because (i) the receiver of accept_entry
is not e
, and (ii) it takes an argument e
.
这篇关于为什么要在Ruby的某个属性上使用一元运算符?即& ;:第一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!