【问题标题】:Ruby koan 280 - where is the reference to to_str?Ruby koan 280 - to_str 的引用在哪里?
【发布时间】:2015-03-11 14:40:25
【问题描述】:

我环顾四周,找不到这个问题:
对于 ruby​​ koan 280,它告诉我以下下划线部分应该是错误的:

  def test_to_str_allows_objects_to_be_treated_as_strings
    assert_equal __, File.exist?(CanBeTreatedAsString.new) # test passes, if __ is changed to false
  end

好的,好的。但是如何测试to_str 是否允许将对象视为字符串?这是 CanBeTreatedAsString 类,它包含一个 to_str 方法:

  class CanBeTreatedAsString
    def to_s
      "string-like"
    end

    def to_str
      to_s
    end
  end

...但这与上面的 assert_equal 代码有什么关系? .exist? 需要一个字符串吗? 本页:
http://www.ruby-doc.org/core-2.2.0/File.html#method-c-exist-3F
表示参数可以是 IO 对象。某些方法是否特定于它们接收的参数类型?如果是这样,我怎么知道?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    File.exist? 接受字符串或 IO。它的部分工作方式是在对象上调用to_str。一个字符串为to_str 返回自身。否则,它应该只在可以用作字符串的对象上实现。

    由于 Ruby 的鸭子类型约定,没有一个简单的方法来判断。然而,通常,如果一个方法接受一个字符串,那么它将调用String.try_convert(它使用to_str)来允许鸭子类型。以类似的方式,许多期望 int 的对象调用 Integer.try_convert(它调用 to_int)来转换参数。

    这里是关于各种转换协议的更多信息:http://pivotallabs.com/messages-not-types-exploring-rubys-conversion-protocols/

    编辑:忘记添加你怎么知道

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 2021-05-13
      • 2020-09-27
      相关资源
      最近更新 更多