Reputation: 15069
I'm just diving into Procs, blocks, and lambdas. I'm noodling around trying different things, but I'm unsure as to why this doesn't work:
def iterate(ary, &code)
ary.each_with_index do |n, i|
ary[i] = code.call(n)
end
end
iterator = Proc.new do |n|
n ** 2
end
p iterate([1,2,3], iterator)
# `iterate': wrong number of arguments (2 for 1) (ArgumentError)
Upvotes: 0
Views: 70
Reputation: 8710
That's because & symbol before the last method's parameters is intended for explicit definition of block as parameter.
In your case you have 2 ways: 1) Use proc parameter instead of block:
def iterate(ary, code)
ary.each_with_index do |n, i|
ary[i] = code.call(n)
end
end
iterator = Proc.new do |n|
n ** 2
end
p iterate([1,2,3], iterator) # => [1, 4, 9]
or 2) Use block instead of proc creation:
def iterate(ary, &code)
ary.each_with_index do |n, i|
ary[i] = code.call(n)
end
end
p iterate([1,2,3]) { |n| n ** 2 } # => [1, 4, 9]
Upvotes: 3
Reputation: 11705
I think that as you're passing in a proc (rather than a block), you don't need the &
in front of the code
parameter in the method definition.
Upvotes: 1