Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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?


The 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).


Yes 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 ...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: