------art_41081_23927689.1186988457525
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

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  tr
    end
    def to_s
      @value
    end
    def to_str
      to_s
    end
  end

irb(main):038:0> x  .new("hello")
#<B:0x27f1550 @valueello">

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  .new("hello")
     assert_equal("hello", x)
   end
 end

Which failed to my surprise.

  1) Failure:
test_equality(MyTest) [(irb):49]:
<"hello"> expected but was
<#<B:0x27549bc @valueello">>.

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  tr
   end
   def to_s
     @value
   end
   def to_str
     to_s
   end
 end

irb(main):023:0* a  .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

------art_41081_23927689.1186988457525--