【问题标题】:Ruby koans: Koan 262 - what is going on here?Ruby koans:Koan 262 - 这是怎么回事?
【发布时间】:2015-01-06 10:19:28
【问题描述】:

一直在研究 Ruby koans,我达到了 262。我已解决如下:

def test_catching_messages_makes_respond_to_lie
    catcher = AllMessageCatcher.new

    assert_nothing_raised do
      catcher.any_method
    end
    assert_equal false, catcher.respond_to?(:any_method)
  end

...但我不知道这段代码在做什么。我查看了 assert_nothing_raised,但文档的解释非常稀疏和深奥。我知道这节课应该教我respond_to?在某些情况下“撒谎”,但这里的情况是什么?

:any_method 不存在吗?如果它在 assert_nothing_raised 的块中定义,它是否不存在?简而言之,这段代码到底发生了什么?

谢谢。

编辑

这是 WellBehavedFooCatcher 类:

class WellBehavedFooCatcher
    def method_missing(method_name, *args, &block)
      if method_name.to_s[0,3] == "foo"
        "Foo to you too"
      else
        super(method_name, *args, &block)
      end
    end
  end

【问题讨论】:

    标签: ruby


    【解决方案1】:

    assert_nothing_raised 在给定块中没有引发任何内容时断言成功;-) 在这种情况下,当方法调用成功时。

    关于方法调用是否成功,即使没有使用此名称的方法:Ruby 有一个特殊方法 method_missing,当原始方法不存在时会调用它:

    class A
      def method_missing(the_id)
        puts "called #{the_id.inspect}"
      end
    end
    
    A.new.foo
    

    这会给你一个called :foorespond_to? 调用只是检查对象是否直接 响应方法调用,因此如果method_missing 正在响应,它将返回 false。

    【讨论】:

    • 感谢您的回复。我仍然不明白为什么 assert_nothing_raised 在那里。不是respond_to吗?只是检查一个 :any_method 方法?假设 missing_method 正在做它的工作,你会期望它返回 true,但教训是它返回 false,作为一个“惊喜”,对吗?那么 assert_nothing_raised 在做什么呢?为什么它还在那里?
    • @moosefetcher 我添加了更多解释。 assert_nothing_raised 用于向您显示方法调用成功(由于 method_missing)但 respond_to? 返回 false(因为对象没有真正响应消息)
    • 啊——我明白了!再次感谢。我不确定这是否值得再问一个问题,但我也不清楚为什么在那个 koan ruby​​ 文件中,之前定义了几行的“WellBehavedFooCatcher”类能够在不调用“super”时调用“super”从任何东西继承...有什么想法吗?
    • All classes derive from BasicObject(如果不存在其他超类则直接,如果存在超类则间接)。
    【解决方案2】:

    换一种说法……

    catcher 是一个类的实例,它响应对其调用的任何方法(通过使用method_missing 捕获)。

    调用catcher.any_method 显然成功了。

    然而,调用 catcher.respond_to?(:any_method) 显然返回 false。

    所以捕获消息会使respond_to? 撒谎。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-06
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 2022-01-23
      • 2020-04-03
      • 2018-06-20
      相关资源
      最近更新 更多