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,entriesis an array, and there are three methodsmap,sort_by, andmapchained.sort_by(&:last)is equivalent tosort_by{|x| x.last}.map(&:first)is the same asmap{|x| x.first}. The reason the firstmapdoes not use&:...is because (i) the receiver ofaccept_entryis note, and (ii) it takes an argumente.