Ruby:想要将对象用作字符串
发布时间:2020-12-17 01:29:52 所属栏目:百科 来源:网络整理
导读:我正在使用一个库,它使用字符串作为ID.我想创建一个可以代替这些ID的类,但看起来像是现有代码的字符串.例如.我有一个现有的测试,看起来像这样: require 'test/unit'class IdString Hash def initialize(id) @id = id end def to_s @id endendclass TestGet
我正在使用一个库,它使用字符串作为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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |