4 ms·
true, but for this it would be fine(?): x = 4 1.upto(5) do |y| x = y puts x end puts "after the block x is #{x} So the problem is
by Tichy 18y ago
true, but for this it would be fine(?):
x = 4
1.upto(5) do |y|
x = y
puts x
end
puts "after the block x is #{x}
So the problem is only the parameter to the block?
- fendale 18y agoYes I think so - your example will still print "after the block x is 5", but in that case that probably is what you would expect. Maybe my head has just gone blank, but I cannot think of a way to get a local called 'x' inside that block that is in scope only within the block. In Perl you would have done my $x = 5; foreach my $i in (1..5) { my $x = $i; ... } And it would have given you a new 'block local' and left your original x alone, but I cannot think of how you can do the equivalent of 'my' in Ruby ...
- KirinDave 18y agoThe problem is that Ruby's scoping rules aren't consistent. Sometimes it appears lexically scoped, but sometimes it acts dynamically scoped. Sometimes this leads to funny looking code (if you know to avoid it) or truly inscrutable bugs (if you don't).