Ruby + Tk command binding - scope issue?

So I have this application

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 a local variable NameError: undefined or the method `my_fancy_function 'for # <TkButton: ..."

I am sure that I am missing something trivial related to the scope ... how can I bind this command to the button correctly?

Edit: Well, if I change my block my_fancy_buttonto parameters, i.e.

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

Then it works. But why?

+3
source share
1 answer

if you put

p self

int block of do ... endyour code, then you will probably find out that the current area is different from your objectFoo

+4
source

Source: https://habr.com/ru/post/1722704/


All Articles