gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:48:15 26 4
gpt4 key购买 nike

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

关于Ruby:想要将对象用作字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17084372/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com