Ruby + Tk command binding - scope issue?

2019-02-18 15:54发布

问题:

So I have this app

require 'tk'
class Foo
  def my_fancy_function
    puts "hello, world!"
  end

  def initialize
    @root = TkRoot.new{title "Hello, world!"}
    frame = TkFrame.new
    my_fancy_button = TkButton.new(frame) do
      text "Press meee"
      command {my_fancy_function}
      pack
    end
    frame.pack
    Tk.mainloop
  end
end

bar = Foo.new

But if I press the button, I get "NameError: undefined local variable or method `my_fancy_function' for #<TkButton:..."

I'm pretty sure I'm missing something trivial related to scope... how do I bind that command to the button correctly?

Edit: Okay, if I change my my_fancy_button block to parameters, i.e.

my_fancy_button = TkButton.new(frame, :text => "Press meee", :command => proc{my_fancy_function}).pack

Then it works. But why?

回答1:

if you put a

p self

int the do ... end block of your code, then you'll probably find out that the current scope is different than your Foo object



标签: ruby scope tk