def reverse_words(s)
s.split.map(&:reverse).join(' ')
end
This code reverses each word in a sentence. But I do not understand "&:" in the code. Can someone explain that to me?
def reverse_words(s)
s.split.map(&:reverse).join(' ')
end
This code reverses each word in a sentence. But I do not understand "&:" in the code. Can someone explain that to me?
map
expects a code block that takes one argument. What you would normally do is to call reverse on that argument:
map {|elt| elt.reverse }
With the &
syntax you can shorten this to
map(&:reverse)
The colon is there to make a symbol out of the name reverse
.
The &
means that reverse
is referencing a function, not a block.
This method assumes that the caller will pass it a String object.
The &
tells the map method that the input is a reference to a method and not a standard block