DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

The ary.map(&:to_s), what is this?

👍 Instant summary

They are equal.

# ary = [:jack, :justin, :jojo]
ary.map(&:to_s) === ary.map{|obj| obj.to_s}
# => true

ary.map(&:to_s)
# => ["jack", "justin", "jojo"]

ary.map{|obj| obj.to_s}
# => ["jack", "justin", "jojo"]

🦄 Understanding

1. The & pass Proc object as a block.

The & in arg, ruby pass the Proc object as a block.

📚 map(&b) (Japanese)

2. automated to_proc

You may have a question that the to_s isn't a Proc object. That's right 👍 and, ruby automatically calls Symbol#to_proc before blocknized by the &.

It means that ..,

ary.map(&:to_s) === ary.map(&:to_s.to_proc)
# => true

3. Symbol#to_proc method

Symbol#to_proc

Returns a Proc object which respond to the given method by sym.

ary.map(&:to_s.to_proc) === ary.map(&Proc.new{|obj| obj.to_s })
# => true

​​

Sumarry

They are same.

ary.map(&:to_s)
ary.map(&:to_s.to_proc)
ary.map(&Proc.new{|obj| obj.to_s })
ary.map{|obj| obj.to_s}

🔗 Parent Note

Top comments (1)

Collapse
 
n350071 profile image
n350071🇯🇵

Oh.., Thank you! I will fix my explain!