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 ??
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With