【问题标题】:Ruby: Want to use object as stringRuby:想要将对象用作字符串
【发布时间】:2013-06-09 16:18:25
【问题描述】:

我正在使用一个始终使用字符串作为 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 为字符串的现有代码的情况下解决此问题?

【问题讨论】:

    标签: ruby


    【解决方案1】:

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

    def to_str
      @id
    end
    

    【讨论】:

    【解决方案2】:

    出现您的问题是因为您继承自 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
    

    【讨论】:

    • 不,即使我从 Hash 中删除继承,我也会遇到同样的问题。此外,我需要从 Hash 继承该类的其他功能。
    • 马雷克的答案是对的。我已经编辑了我的代码以使用to_str
    猜你喜欢
    • 2017-12-08
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2016-12-17
    • 2020-04-09
    • 2019-07-14
    • 1970-01-01
    相关资源
    最近更新 更多