开发者

Why would one use the unary operator on a property in ruby? i.e &:first [duplicate]

This question already has answers h开发者_JAVA技巧ere: Closed 11 years ago.

Possible Duplicate:

Ruby/Ruby on Rails ampersand colon shortcut

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

The part I don't get is what is &:last and &:first doing?!? It appears as madness!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜