【问题标题】:Ruby yield newbie issueRuby 产量新手问题
【发布时间】:2012-07-07 13:27:06
【问题描述】:

我最近开始使用 Ruby,对它很陌生。我目前的目标是使用一个名为 retort 的 ruby​​ 模块,我的问题是我不明白 configure 方法,它看起来像这样:

def configure
    config = Config.new
    yield config
    @@service = XMLRPC::Client.new2(config.url)
end

Config 类很简单,看起来像:

class Config
    attr_accessor :url
end

我试图创建一个小例子来玩一下,以了解它应该如何工作:

class TestClass
  def test_method
     config = String.new
     yield config
     p config
  end
end

d = TestClass.new
d.test_method { 'test string' }

当然它不会返回“测试字符串”而是一个空字符串。

感谢您的帮助:)

【问题讨论】:

    标签: ruby yield


    【解决方案1】:

    您能更清楚地了解什么让您感到困惑吗?这段代码对你有意义吗?

    class TestClass
      def test_method
        config = yield
        p config
      end
    end
    
    d.test_method { "test string" }
    

    yield 语句调用该块。该块返回一个字符串,该字符串被分配给test_method 中的config 变量,然后被打印。这是否使它更清楚?

    在您的代码中,yield config 行正在调用块,同时传入刚刚实例化的 Config 对象。例如:

    def foo
      s = "a string"
      yield s
      p "In foo printing " + s
    end
    
    foo { |x| p "In block printing " + x }
    

    【讨论】:

    • 这更清楚了,是的,谢谢拉里。但是,我仍然在为那个配置方法和配置对象而苦恼。 “产量配置”究竟做了什么?我怎样才能这样定义配置?
    • yield config 将刚刚创建的Config 对象传递给块。就像,假设块是configure { | c | c.url = "http://google.com" } ...块中的Config 将被传递给块,它可以分配给它的url 字段,然后控制流回到@987654333 @ 方法及其分配的 url。 (并将其传递给 XMLRPC Client 等)
    猜你喜欢
    • 1970-01-01
    • 2017-02-13
    • 2016-06-11
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 2011-01-11
    • 2011-02-01
    • 2012-07-16
    相关资源
    最近更新 更多