Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does &:to_s mean in b.map(&:to_s) [duplicate]

Tags:

ruby

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

like image 805
SuperManEver Avatar asked Sep 03 '25 17:09

SuperManEver


1 Answers

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