【问题标题】:How to implement to_str or to_s如何实现 to_str 或 to_s
【发布时间】:2015-01-03 11:07:15
【问题描述】:

我有一个应该用作字符串的类,并且始终是字符串(即使为空)。该对象将始终具有字符串表示形式。以下是我班的一个例子:

class Something
    def initialize
        @real_string_value = "hello"
    end
    def to_s
        return @real_string_value
    end
    def to_str
        return @real_string_value
    end
end

text = Something.new
puts("#{text}") #=> #<Something:0x83e008c>

我在 minitest 上运行了这个测试:

assert_equal(
    "",
    "#{@text}",
    "Unchanged class should convert to empty by default"
)

上面的测试失败了。为什么我的类没有转换成字符串?

【问题讨论】:

  • 我得到了helloideone.com/ofHJ4m
  • 为什么在测试代码中使用#{@text}" 而不是#{text}
  • 测试作用于在 minitest setup 方法中创建的实例变量。
  • 我认为断言应该是:assert_equal("hello", "#{@text}"),因为to_s返回分配给@real_string_value的字符串。
  • 在这个例子中,是的,但对于我的测试没有。如果没有为类分配值,它应该返回一个空字符串。不过,让我给它赋值hello 看看它是否有效。

标签: ruby string type-conversion implicit-conversion magic-methods


【解决方案1】:

如果作为脚本运行,代码会按预期打印hello

如果您在irb 或类似的交互式shell 中运行代码,它会使用inspect 而不是to_s 方法用于以下行:

text = Something.new

你需要定义inspect:

class Something

    ...

    def inspect
        to_s
    end
end

【讨论】:

    猜你喜欢
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2011-10-27
    • 1970-01-01
    • 2015-11-26
    相关资源
    最近更新 更多