Dodzi Dzakuma
Dodzi Dzakuma

Reputation: 1426

How to implement to_str or to_s

I have a class that should be used as a string and will always be a string (even if empty). The object will always have a string representation. The following is an example of my class:

class Something
    def initialize
        @real_string_value = "hello"
    end
    def to_s
        return @real_string_value
    end
    def to_str
        return @real_string_value
    end
end

text = Something.new
puts("#{text}") #=> #<Something:0x83e008c>

I ran this test on minitest:

assert_equal(
    "",
    "#{@text}",
    "Unchanged class should convert to empty by default"
)

The test above fails. Why isn't my class converted to a string?

Upvotes: 0

Views: 520

Answers (1)

falsetru
falsetru

Reputation: 369274

The code print hello as expected if it's run as a script.

If you run the code in irb or similar interactive shell, it uses inspect instead of to_s method for the following line:

text = Something.new

You need to define inspect:

class Something

    ...

    def inspect
        to_s
    end
end

Upvotes: 1

Related Questions