Ruby(Shoes) - 等待函数返回值

时间:2008-12-19 16:40:51

标签: ruby function shoes

我有一个向用户提供组合框的功能。

def select_interface(interfaces)
  list_box :items => interfaces do |list|
    interface = list.text
  end
  ### ideally should wait until interface has a value then: ###
  return interface
end

程序的其余部分取决于此组合框中的选择。

我想找到一种方法让ruby等待组合框的输入,然后执行剩下的代码。

shoes中有一个名为 ask 的类似功能会等待用户的输入。

interface =  ask("write your interface here")

如何在Ruby / shoes中实现“等到变量有值”功能?

1 个答案:

答案 0 :(得分:2)

我花了一段时间才明白你的问题:)我开始写一篇关于GUI应用程序整个理论的长篇答案。但是你已经拥有了所需的一切。 list_box采用的块实际上是它的更改方法。你告诉它什么时候改变了。当你得到你想要的值时,只需将程序的其余部分推迟运行。

Shoes.app do 
  interfaces = ["blah", "blah1", "blah2"]
  # proc is also called lambda
  @run_rest_of_application = proc do
    if @interface == "blah"
      do_blah
    # etc
  end

  @list_box = list_box(:items => interfaces) do |list|
    @interface = list.text
    @run_rest_of_application.call
    @list_box.hide # Maybe you only wanted this one time?
  end
end

这是所有GUI应用程序背后的基本思想:构建初始应用程序然后等待“事件”,这将创建新的状态供您响应。例如,在ruby-gnome2中,您将使用带有Gtk::ComboBox的回调函数/块来更改应用程序的状态。像这样:

# Let's say you're in a method in a class
@interface = nil
@combobox.signal_connect("changed") do |widget| 
  @interface = widget.selection.selected
  rebuild_using_interface
end

即使在工具包之外,您也可以使用Ruby的Observer module获得“免费”事件系统。希望这有帮助。

相关问题