user1934428
user1934428

Reputation: 22225

How to use a Proc as a block

Given an array myarr and a method foo that is understood by each element of the array, I can produce a new array by:

mapper = :foo
newarr = myarr.map(&mapper)

because the & shortcut turns the symbol stored in mapper into a Proc.

Suppose mapper is not a Symbol, but is already a Proc instance. This, then:

mapper = :foo.to_proc
newarr = myarr.map(mapper)

raises an error because Array#map does not accept a parameter.

Of course I can do:

newarr = myarr.map {|x| mapper.call(x)}

but I wonder whether there is a shortcut trick (similar to &:foo) that I can use here.

Upvotes: 2

Views: 53

Answers (1)

sawa
sawa

Reputation: 168071

Just do:

newarr = myarr.map(&mapper)

A Proc instance is an object, whereas a block is not an object. They are not interchangable. You need to convert one to the other using &. In case mapper is a symbol, the effect of & in &mapper is not just to convert mapper into a Proc instance; that is just part of the process of converting/interpreting mapper to/as a block. This is no different when mapper is already a Proc instance; just this intermediate step of converting it to a Proc instance becomes trivial.

Upvotes: 6

Related Questions