1
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?

Makoto
  • 104,088
  • 27
  • 192
  • 230
BufBills
  • 8,005
  • 12
  • 48
  • 90

2 Answers2

1

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.

A Person
  • 1,062
  • 9
  • 17
0

The & means that reverse is referencing a function, not a block.

This method assumes that the caller will pass it a String object.

  1. First the method #splits the string on whitespaces into an array (if the string has no whitespaces it creates an array with the string as the only element)
  2. Calls the Array#map method on the new array and passes it a reference to the String#reverse method.

The & tells the map method that the input is a reference to a method and not a standard block

sdc
  • 2,603
  • 1
  • 27
  • 40
  • This has nothing to do with method references. A method reference would be something like `each(&method(:puts))`. Also, this has nothing to do with `map`. `map` doesn't know whether you pass a block directly or via the unary prefix ampersand operator. – Jörg W Mittag Apr 15 '17 at 07:06