M
Michael Roth
Hello all,
I'm still making progress in learning ruby, but I ran across a problem
with lambda in loops wich gives me real headache until I found it. My
code looked like this:
a = []
for multi in [2, 3, 4, 5]
a << lambda do |n|
n * multi
end
end
for mul in a
puts mul.call(17)
end
I thought, this code will output four numbers 34, 51, 68, 85 but it
doesn't...
Instead it printed four times '85'. Obviously the four created blocks
are all using the same instance of 'multi'.
However, if I rewrite these lines to the following, it works as expected:
def create_mul multi
lambda do |n|
n * multi
end
end
b = []
for multi in [2, 3, 4, 5]
b << create_mul(multi)
end
for mul in b
puts mul.call(17)
end
So my question is: If there is an easy way to get the expected behavior
without a helper function like create_mul()?
In my app the lambdas to create in the loop are really small and I don't
would like to put their code outside the loop by reason of clarity.
Michael Roth
I'm still making progress in learning ruby, but I ran across a problem
with lambda in loops wich gives me real headache until I found it. My
code looked like this:
a = []
for multi in [2, 3, 4, 5]
a << lambda do |n|
n * multi
end
end
for mul in a
puts mul.call(17)
end
I thought, this code will output four numbers 34, 51, 68, 85 but it
doesn't...
Instead it printed four times '85'. Obviously the four created blocks
are all using the same instance of 'multi'.
However, if I rewrite these lines to the following, it works as expected:
def create_mul multi
lambda do |n|
n * multi
end
end
b = []
for multi in [2, 3, 4, 5]
b << create_mul(multi)
end
for mul in b
puts mul.call(17)
end
So my question is: If there is an easy way to get the expected behavior
without a helper function like create_mul()?
In my app the lambdas to create in the loop are really small and I don't
would like to put their code outside the loop by reason of clarity.
Michael Roth