3

I am novice in ruby and this question may seem silly for you, but I haven't found any reasonable explanation.

for example I have

array = [1,2,3,4,5,6]

and I'd like to make from this array of strings for some reasons

One of the ways is to do like this:

str_arr = array.map {|i| i.to_s}

at some web resource I've found the following:

array.map(&:to_s)

this does the same thing. Could someone explain what &:to_s means ??

Sergio Tulentsev
  • 219,187
  • 42
  • 361
  • 354
SuperManEver
  • 2,153
  • 5
  • 26
  • 35

1 Answers1

2

It's syntactic sugar that turns to_s into a block that can be passed to map, sort of like passing to_s as a function object. Basically, it's shorthand for

array.map(&:to_s.to_proc)

# Or to see the individual steps:
proc = :to_s.to_proc
array.map(&proc)

See also What does map(&:name) mean in Ruby?.

Community
  • 1
  • 1