Closures and for loops in Ruby

前端 未结 2 1912
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 07:15

I\'m kind of new to Ruby and some of the closure logic has me a confused. Consider this code:

array = []
for i in (1..5)
  array << lambda {i}
end
arra         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-13 07:34

    What version of Ruby are you running this on? 1.8 does not have block scope for local variables, so j is still hanging around (and equal to 5) even after the end of the for.

提交回复
热议问题