当前位置 : 主页 > 编程语言 > ruby >

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

来源:互联网 收集:自由互联 发布时间:2021-06-23
我正在使用一个库,它使用字符串作为ID.我想创建一个可以代替这些ID的类,但看起来像是现有代码的字符串.例如.我有一个现有的测试,看起来像这样: require 'test/unit'class IdString Hash def
我正在使用一个库,它使用字符串作为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:无法将IdString转换为String

有没有办法解决这个问题而不改变所有希望id为字符串的现有代码?

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

def to_str
  @id
end
网友评论