Nasir Khan wrote:
> Hi,
Greetings Nasir,

>  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
> <#<B:0x27549bc @value="hello">>.
> 
> 1 tests, 1 assertions, 1 failures, 0 errors
Okay, as the results showed, an object "x" of class MyTest does not 
equal the
string results of the method  .to_str called on the x object.

assert_equal ("hello", x.to_str)

is what you want :)

> 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.
No surprise here, either. You have added a method, to_str to the String 
class,
but when you instantiated the Object you did not make any assignment to 
the string itself.

If you say, for example:

b= String.new
puts b

you would get the same result, because this is essentially the same 
thing.
In your a class, a.to_str should work, I believe, but in my mind, all 
bets are off because you are changing the behavior of the built-in 
String class, which is generally "a bad thing" unless you are very 
careful.

Cheers,

Howard
-- 
Posted via http://www.ruby-forum.com/.