Ruby中如何将对象转换为字符串表示形式?

更新于
2026-10-10 03:45:20
0阅读来源:SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计250个文字,预计阅读时间需要1分钟。

Ruby中如何将对象转换为字符串表示形式?

我在使用一个库,它用字符串作为ID。我想创建一个类来替代这些ID,但看起来现有代码中直接使用字符串。例如,我有一个现有的测试,看起来是这样:

pythonrequire '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方法,该方法用于隐式转换:

Ruby中如何将对象转换为字符串表示形式?

def to_str @id end

本文共计250个文字,预计阅读时间需要1分钟。

Ruby中如何将对象转换为字符串表示形式?

我在使用一个库,它用字符串作为ID。我想创建一个类来替代这些ID,但看起来现有代码中直接使用字符串。例如,我有一个现有的测试,看起来是这样:

pythonrequire '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方法,该方法用于隐式转换:

Ruby中如何将对象转换为字符串表示形式?

def to_str @id end