Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Want to use object as string

Tags:

ruby

I am working with a library which uses strings as ids throughout. I want to make a class which can be used in place of these ids, but looks like a string to the existing code. E.g. I have an existing test which looks like this:

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

Unfortunately this fails with:

TypeError: can't convert IdString to String

Is there a way to fix this without changing all the existing code which expects ids to be strings?

like image 489
Stefan Avatar asked Nov 25 '25 01:11

Stefan


1 Answers

You should implement to_str method, which is used for implicit conversions:

def to_str
  @id
end
like image 197
Marek Lipka Avatar answered Nov 26 '25 18:11

Marek Lipka