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!