From: Nasir Khan Date: 2007-08-13T16:00:52+09:00 Subject: to_str behavior ------=_Part_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 = str end def to_s @value end def to_str to_s end end irb(main):038:0> x = B.new("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. 1) Failure: test_equality(MyTest) [(irb):49]: <"hello"> expected but was <#>. 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 ------=_Part_41081_23927689.1186988457525--