L
Len Lawrence
My understanding of Ruby scoping rules must be deficient in some way
because after three years coding in Ruby and reading numerous books about
the language I still cannot fathom why the following code works but with
a seemingly innocuous change it fails to run as expected.
u = [ ]
v = [ ]
which = [ ]
@subtypes.each_key { |k| which << [@subtypes[k], k] }
which.sort!
n = @subtypes.length - 1
0.upto( n ) { |jay| v[jay] = lambda { @extra.value = @subtypes[which
[jay][1]] } }
0.upto( n ) do |i|
category = which[1]
u = TkButton.new( altbar ) do
text category
font Helvetica
relief 'flat'
background Panel
foreground 'orange'
highlightthickness 0
command v
pack 'side' => 'left', 'padx' => 1
end
end
This snippet adds four buttons to a Tk interface. Clicking any one of
them is supposed to change the value of an entry field elsewhere in the
gui via a TkVariable. The code works as shown but if jay is replaced by j
in the definition of the lambdas the value of the Tk variable sticks at
the last value of j, in this case 3; i.e. clicking any one of the
labelled buttons returns 3 always. j is used elsewhere but here it is
local to the 0 to n loop. What I suspect is that it is not a scope
problem at all but something to do with the implementation of Tk in Ruby.
??
because after three years coding in Ruby and reading numerous books about
the language I still cannot fathom why the following code works but with
a seemingly innocuous change it fails to run as expected.
u = [ ]
v = [ ]
which = [ ]
@subtypes.each_key { |k| which << [@subtypes[k], k] }
which.sort!
n = @subtypes.length - 1
0.upto( n ) { |jay| v[jay] = lambda { @extra.value = @subtypes[which
[jay][1]] } }
0.upto( n ) do |i|
category = which[1]
u = TkButton.new( altbar ) do
text category
font Helvetica
relief 'flat'
background Panel
foreground 'orange'
highlightthickness 0
command v
pack 'side' => 'left', 'padx' => 1
end
end
This snippet adds four buttons to a Tk interface. Clicking any one of
them is supposed to change the value of an entry field elsewhere in the
gui via a TkVariable. The code works as shown but if jay is replaced by j
in the definition of the lambdas the value of the Tk variable sticks at
the last value of j, in this case 3; i.e. clicking any one of the
labelled buttons returns 3 always. j is used elsewhere but here it is
local to the 0 to n loop. What I suspect is that it is not a scope
problem at all but something to do with the implementation of Tk in Ruby.
??