I’ve just recently been getting to know ruby and the ruby Tk library and
have run into a block scoping problem [apparently] that I don’t really
understand (I’m a long-time C programmer, mostly at the systems and
library levels, and have little experience with VHLLs such as ruby).
I’ve included below a cobbled up example that demonstrates the problem
that has been driving me completely batty.
Basically, why is the “mybutton” method reference not contained within
the binding of the block passed to the TkButton.new method though it is
clearly within the scope of the initialize_n methods?
I guess my question boils down to is how much of the block’s context is
actually contained within its binding, i.e., how far out does it extend?
Obviously, it extends at least to that of the method within which it
appears. Why not to all symbols visible within the class definition
(as, apparently, it doesn’t)?
I do realize that the actual block passed to the “command” method in the
outer block passed to the TkButton.new method is actually executed in
the context of the button code itself somewhere in the Tk library and,
therefore, executes in -that- context. However, it’s binding should
carry over some of the context in which it was created. How much (i.e.,
to what extent)?
Any references to books, online docs, code examples, ruby interpreter
sources, etc., in this regard would also be much appreciated.
Additionally, any insights as to what goes on “behind the scenes” in
ruby would be very helpful.
Thanks!
Phil
----- Begin ruby code -----
#!/usr/bin/ruby -w
require ‘tk’
class MyButton
def myexit
exit
end
Doesn’t work: “myexit” out of scope in block. Why?
def initialize_1
mybutton = TkButton.new do
text “EXIT”
command { myexit }
pack
end
end
Works: refs “myexit” outside of block.
Note that “myexit” -is- visible within the initialize_2 method!?!
def initialize_2
mybutton = TkButton.new do
text “EXIT”
pack
end
mybutton.command { myexit }
end
Works: creates local proc object to pass to block.
Note that “myexit” -is- visible within the initialize_3 method!?!
def initialize_3
proc_myexit = lambda { myexit }
mybutton = TkButton.new do
text “EXIT”
command proc_myexit
pack
end
end
Pick one of “initialize_[123]” to perform the test cases.
def initialize
initialize_1
#initialize_2
#initialize_3
Tk.mainloop
end
end
MyButton.new
----- End Ruby Code -----