Hi,
I have two related questions on to_str behavior. AFAIK to_str does
automatic
coercion to string wherever one is required, it is to be provided for
objects that exhibit string like behavior. But this mental model did not
match up with my test -
Consider a simple class
class B
def initialize(str)
@value = str
end
def to_s
@value
end
def to_str
to_s
end
end
irb(main):038:0> x = B.new(“hello”)
=> #<B:0x27f1550 @value=“hello”>
irb(main):042:0> a = “hello”+x
=> “hellohello”
So far so good. Concatenation automatically happend. Then I went on to
write
a test -
class MyTest < Test::Unit::TestCase
def test_equality
x = B.new(“hello”)
assert_equal(“hello”, x)
end
end
Which failed to my surprise.
- Failure:
test_equality(MyTest) [(irb):49]:
<“hello”> expected but was
<#<B:0x27549bc @value=“hello”>>.
1 tests, 1 assertions, 1 failures, 0 errors
Trying to experiment further I made my class B a subclass of String just
to
check the test -
class B < String
def initialize(str)
@value = str
end
def to_s
@value
end
def to_str
to_s
end
end
irb(main):023:0* a = B.new(“hello”)
=> “”
irb(main):024:0>
irb(main):025:0*
irb(main):026:0* puts a
=> nil
Which surprised me even more.
Any explanation of these two counter-intuitive behaviors will be greatly
appeciated.
Thanks
Nasir