Ricky
Ricky

Reputation: 35

Attempting to use an array of Procs by using #.each on the Array but getting Error

We have to write a method, chain_map, that accepts any value and an array of procs as an argument. The method should return the final result of feeding the value through all of the procs. For example, if the array contains three procs, then: -the value is given to the first proc -the result of the first proc is given to the second proc

I wrote:

def chain_map(val, *prcs)
    new_val = val
    prcs.each do |prc|
        new_val = prc.call(new_val)
    end
    new_val
end

When I run the code with the following:

add_5 = Proc.new { |n| n + 5 }
half = Proc.new { |n| n / 2.0 }
p chain_map(25, [add_5, half])          # 15.0

I get the following error on the line where it says new_val = prc.call(new_val): undefined method `call' for #Array:0x00007fffd40268c8 (NoMethodError)

When I am using .each, its iterating over each proc stored in the array(prcs), so I don't see why it is giving an error.

Any help is appreciated.

Upvotes: 0

Views: 430

Answers (1)

Fabio
Fabio

Reputation: 32455

chain_map's second argument defined with splat operator, that mean remain arguments after val argument given by the caller will be wrapped into array.

But because you passing array of the procs as single argument chain_map(25, [add_5, half]), given array will be wrapped with another array in the method.

Don't wrap procs with the array

chain_map(25, add_5, half) 

Or use splat operator on the array of procs if you build procs dynamically

chain_map(25, *procs) 

Alternative approach by using reduce

result = procs.reduce(25) { |value, proc| proc.call(value) } 

Upvotes: 0

Related Questions