Anyone care to explain this? I thought ‘puts’ always called the
’to_s’ method on its arguments. Or are classes and structs not
designed to be mixed?
Thanks,
Gavin
irb(main):006:0> X = Struct.new(:x)
=> X
irb(main):007:0> x = X.new(6)
=> #
irb(main):008:0> class X
irb(main):009:1> def to_s
irb(main):010:2> -15
irb(main):011:2> end
irb(main):012:1> end
=> nil
irb(main):013:0> puts x
#<X:0x10167548>
=> nil
irb(main):014:0> puts x.to_s
-15
=> nil
In message “Problem with class, struct, and to_s” on 03/07/26, Gavin Sinclair gsinclair@soyabean.com.au writes:
Anyone care to explain this? I thought ‘puts’ always called the
‘to_s’ method on its arguments. Or are classes and structs not
designed to be mixed?
Because your “to_s”, which should return a string representation of
the receiver, did return an integer, so that “puts” (and its internal
conversion method) was forced to use the default string conversion
method.
(I’m in the habit of writing test methods in irb that just return an
integer…)
So what happens internally when #puts calls #to_s and it doesn’t get a
String? The net result is that it prints the output of #inspect, by
the look of it, which seems a bit weird.
Gavin
···
On Saturday, July 26, 2003, 2:54:28 AM, ts wrote:
irb(main):009:1> def to_s
irb(main):010:2> -15
irb(main):011:2> end
I hope that you know that -15 is not a String object
So what happens internally when #puts calls #to_s and it doesn't get a
String? The net result is that it prints the output of #inspect, by
the look of it, which seems a bit weird.
Well it call the equivalent of #inspect, and you are lucky because if
plruby receive a Fixnum when it expect a String : it think that you are
trying to crack it and it stop immediately with an error message :-)))