Annoying block variable behaviour!

Hi, I remember reading somewhere that the Ruby handling of block local
variables is deprecated and will be fixed, but for now it gives very
anoying
behaviour. For example:

This is obvious and correct:

a)

[1,2,3,4].each { |kk| kk=true }
=> [1, 2, 3, 4]

kk
=> NameError: undefined local variable or method `kk’ for main:Object

But what about this???:

b)

kk = false
[1,2,3,4].each { |kk| kk=true }
=> [1, 2, 3, 4]

kk
=>true

So, “kk” is defined as “false” and later in a block it’s “true”, but
this
value must not be visible outside the block. In a) it doesn’t occur (so
OK)
but in b) is annoying, kk is finally “true” just because in a block it
was “true” and before it it was defined in top level.

IMHO it makes no sense at all. Is there any explanation for this last
case?

Thanks for any comment about it.

From: Iñaki Baz C. [mailto:[email protected]]

but in b) is annoying, kk is finally “true” just because in a

block it was “true” and before it it was defined in top level.

IMHO it makes no sense at all. Is there any explanation for

this last case?

the ruby community is divided when it comes to this shadowing behaviour
of block locals and block params. see the ruby archives.

on your case, ruby1.9 may satisfy

irb(main):005:0* RUBY_VERSION
=> “1.9.0”
irb(main):006:0> [1,2,3,4].each { |kk| kk=true }
=> [1, 2, 3, 4]
irb(main):007:0> kk
NameError: undefined local variable or method `kk’ for main:Object

irb(main):008:0> kk=false
=> false
irb(main):009:0> [1,2,3,4].each { |kk| kk=true }
=> [1, 2, 3, 4]
irb(main):010:0> kk
=> false

and it comes w warnings too just in case you want to be safe :wink:

C:\ruby1.9\bin>ruby1.9 -we "kk=false; [1,2,3,4].each { |kk| kk=true } "
-e:1: warning: shadowing outer local variable - kk

kind regards -botp

2008/4/16, Peña, Botp [email protected]:

the ruby community is divided when it comes to this shadowing behaviour of block locals and block params. see the ruby archives.

Thanks, I’ll look for it.

irb(main):008:0> kk=false
=> false
irb(main):009:0> [1,2,3,4].each { |kk| kk=true }
=> [1, 2, 3, 4]
irb(main):010:0> kk
=> false

and it comes w warnings too just in case you want to be safe :wink:

Great to know it, thanks a lot :slight_smile: