From: Hidetoshi NAGAI Date: 2006-03-08T23:37:03+09:00 Subject: Re: Ruby/Tk: How to access surrounding class from Tk Callback? From: u235321044@spawnkill.ip-mobilphone.net (Ronald Fischer) Subject: Re: Ruby/Tk: How to access surrounding class from Tk Callback? Date: Wed, 1 Mar 2006 17:48:37 +0900 Message-ID: > Arigatou gozaimasu! But where can I find the FAQ? If I am right, I'd wrote a same answer on this ML. ;-) > 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. I want to compose Ruby/Tk manuals/documents. But I don't have enough time and collaborators to do that. And it is so hard for me to translate them to English, because I'm poor at English. > > ------< example 1 >------------------------------------------ (snip) > 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? A Proc object keeps its binding. > > ------< example 2 >------------------------------------------ (snip) > Here I have two questions: What is the meaning of the > colon in front of "command", ":command" is a symbol. Current Ruby/Tk can accept a string or a symbol as a key of an option. FYI, a has of options is a little faster than method calls. For example, --------------------------------------------------------------------- action_button=TkButton.new(@root, :text=>"Action!",:command=>cmd) --------------------------------------------------------------------- this calls the Tk interpreter only once. But, --------------------------------------------------------------------- action_button=TkButton.new(@root) { # <= 1 text "Action!" # <= 2 command cmd # <= 3 }) --------------------------------------------------------------------- this calls Tk interpreter three times. > and why can I access @root > now from inside command, but not in my original code? It depends on the difference of scope. In the block given to TkButton.new, 'self' is the button object. But the proc object is defined in the scope of 'initialize'. > > ------< example 3 >------------------------------------------ (snip) > 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. The answer is same as the one for < example 1 >. -- Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)