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
.