Ruby:要将对象用作字符串吗

Ruby:要将对象用作字符串吗,ruby,Ruby,我正在使用一个使用字符串作为ID的库。我想创建一个类,它可以用来代替这些ID,但看起来像是现有代码的字符串。例如,我有一个现有的测试,如下所示: require 'test/unit' class IdString < Hash def initialize(id) @id = id end def to_s @id end end class TestGet < Test::Unit::TestCase def test_that_id_is

我正在使用一个使用字符串作为ID的库。我想创建一个类,它可以用来代替这些ID,但看起来像是现有代码的字符串。例如,我有一个现有的测试,如下所示:

require 'test/unit'
class IdString < Hash
  def initialize(id)
    @id = id
  end

  def to_s
    @id
  end
end

class TestGet < Test::Unit::TestCase
  def test_that_id_is_1234
    id = IdString.new('1234')

    assert_match(/1234/, id)
  end
end
要求“测试/单元”
类IdString<哈希
def初始化(id)
@id=id
结束
def至美国
@身份证
结束
结束
类TestGet
不幸的是,这在以下方面失败:

TypeError:无法将IdString转换为String


有没有一种方法可以在不更改所有期望ID为字符串的现有代码的情况下修复此问题?

您应该实现
to_str
方法,该方法用于隐式转换:

def to_str
  @id
end

您的问题之所以出现,是因为您继承了
哈希
。如果你真正想要的是一根绳子,为什么你需要这个

如果要将ID封装到它自己的单独对象中(您可能需要仔细考虑),只需执行以下操作:

require 'test/unit'

class IdString < Hash
  def initialize(id)
    @id = id
  end

  def to_str
    @id
  end
end

class TestGet < Test::Unit::TestCase
  def test_that_id_is_1234
    id = IdString.new('1234')

    assert_match(/1234/, id)
  end
end
要求“测试/单元”
类IdString<哈希
def初始化(id)
@id=id
结束
def to_str
@身份证
结束
结束
类TestGet
No,即使我从散列中删除继承,我也会遇到同样的问题。另外,我还需要从Hash继承类的其他功能,因为您所追求的是Marek的答案是正确的。我已经编辑了我的代码来使用
to_str
。在我看来,
to_s
to_str
在不同的情况下都被使用。我在哪里可以找到这种情况的文档?这似乎解决了问题,而且非常简单。似乎to_s vs to_str非常复杂:“to_s vs to_str”主题的更多信息: