Stefan
Stefan

Reputation: 9329

Ruby: Want to use object as string

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?

Upvotes: 3

Views: 124

Answers (2)

alexpls
alexpls

Reputation: 1964

Your issue is arising because you're inheriting from Hash. Why do you need to this if what you're really after is a string?

If you want to encapsulate the ID into its own separate object (which you should probably think twice about), just do this:

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

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

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

def to_str
  @id
end

Upvotes: 7

Related Questions