【问题标题】:Ruby (Shoes) - Wait for function to return valueRuby (Shoes) - 等待函数返回值
【发布时间】:2010-09-27 17:52:36
【问题描述】:

我有一个向用户显示组合框的函数。

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 中实现这个“等到变量有值”的功能?

【问题讨论】:

    标签: ruby function shoes


    【解决方案1】:

    我花了一段时间才理解你的问题 :) 我开始写一个关于 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 获得“免费”事件系统。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-07-02
      • 2019-07-25
      • 2016-10-16
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 2020-03-13
      相关资源
      最近更新 更多