3

我正在使用一个使用字符串作为 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

不幸的是,这失败了:

TypeError: can't convert IdString to String

有没有办法在不更改所有期望 id 为字符串的现有代码的情况下解决此问题?

4

2 回答 2

7

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

def to_str
  @id
end
于 2013-06-13T10:12:00.477 回答
0

您的问题出现是因为您继承自Hash. 如果您真正追求的是字符串,为什么需要这样做?

如果您想将 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
于 2013-06-13T10:15:13.597 回答