From: u235321044@... (Ronald Fischer) Date: 2006-03-01T17:48:37+09:00 Subject: Re: Ruby/Tk: How to access surrounding class from Tk Callback? Hidetoshi NAGAI wrote: > From: u235321044@spawnkill.ip-mobilphone.net (Ronald Fischer) > > @root=TkRoot.new() { title "My Form" } > > action_button=TkButton.new(@root) { > > text "Action!" > > command { > > # Do something with @root and @foo > > puts @root.foo # DOES NOT WORK > > } > > } > > It may be a FAQ. Arigatou gozaimasu! But where can I find the FAQ? I was able to locate one only in Japanese, and my Japanese is barely sufficient to order some Yakitori, let alone reading such a FAQ.... :-( Aside from a FAQ, a Ruby/Tk reference manual might be handy. Right now I am "learning" Ruby/Tk by looking at examples I find on the net, and *guessing* how they could work - not a very satisfying means to grasp a new language. > A block given to .new method is > evaluated by .instance_eval(). > That is, in the block, 'self' is the widget object. > So, @root in your button's command is an instance variable > of the button widget. I understand. > To avoid it, you have to give attention to scope of variables. > For example, > ------< example 1 >------------------------------------------ > def initialize(...) > foo = @foo=1234 > ... > root = @root = TkRoot.new() { title "My Form" } > action_button=TkButton.new(@root) { > text "Action!" > command { > # use local variables > puts foo # same as @foo > puts root # same as @root > } > } > action_button.pack("side" => "right"); > end I amazed that this works, but I don't know how. foo is a local variable inside initialize, isn't it? So it should go out of scope as soon as initialize ends. How then can I refer to it from inside my action command? > ------< example 2 >------------------------------------------ > def initialize(...) > @foo=1234 > ... > @root = TkRoot.new() { title "My Form" } > action_button=TkButton.new(@root, > :text=>"Action!", > :command=>proc{ > puts @foo > puts @root > }) > action_button.pack("side" => "right"); > end Here I have two questions: What is the meaning of the colon in front of "command", and why can I access @root now from inside command, but not in my original code? > ------< example 3 >------------------------------------------ > def initialize(...) > @foo=1234 > ... > @root = TkRoot.new() { title "My Form" } > cmd = proc{ > puts @foo > puts @root > } > action_button=TkButton.new(@root) { > text "Action!" > command cmd > } > action_button.pack("side" => "right"); > end This looks clever too. From a design point of view, I like solution 2 best, because it avoids the need for additional variables. Still would like to understand, *why* it works. Ronald -- Spam protected message from: Sent by mn-pg-p-e-b-consultant-3.com from siemens in field com Posted via http://www.usenet-replayer.com