On Saturday, July 19, 2003, at 12:56  PM, Yukihiro Matsumoto wrote:
> |#to_hash is fine by me too, but I don't really know the nuances of
> |to_s/to_str, to_a/to_ary, ...
>
> Longer versions are for implicit conversion.  An object that has
> "to_str" works like a string if it's given as an argument.

While we're on the subject of "to_s" and similar friends, I have a 
question about Array#to_s and Hash#to_s.

I've never found them very useful the way they work by default:

irb(main):026:0> [1, 2, 3, 4].to_s
"1234"

irb(main):028:0> {1 =>2, 3 => 4}.to_s
"1234"

The main problem here is that Array#to_s calls join with the default 
field separator, which for some reason is "".  To me, this isn't 
intuitive.  Is there some historical reason why this behavior exists?  
Even less intuitive to me is Hash#to_s, because the way the conversion 
is done you lose any concept it was a hash.

Both of these default behaviors can be changed by setting $,

irb(main):033:0> $, = ", "
", "
irb(main):034:0> [1, 2, 3, 4].to_s
"1, 2, 3, 4"
irb(main):035:0> {1 =>2, 3 => 4}.to_s
"1, 2, 3, 4"

This is great for an array, but less great for a hash, you still lose 
the key=>value association.

The main issue I have with these default to_s calls is that you seem to 
lose a lot of information in the conversion.  On the other hand, I 
think the output from Array#inspect and Hash#inspect is great.  It's 
easily readable and contains all the info I want.

I'm having trouble coming up with a good example of where having a 
reasonable output from some_random_object.to_s should be useful, but 
how about this:

def giveRating(obj)
   puts "My rating for the movie is #{obj}"
end

irb(main):049:0> giveRating("***")
My rating for the movie is: ***
nil
irb(main):050:0> giveRating("so-so")
My rating for the movie is: so-so
nil
irb(main):051:0> giveRating(7)
My rating for the movie is: 7
nil
irb(main):052:0> giveRating(["good plot", "bad writing"])
My rating for the movie is: good plotbad writing
nil
irb(main):053:0> giveRating({"acting" => 5, "music" => "awful"})
My rating for the movie is: musicawfulacting5
nil

It would be more intuitive to me if the complete default output were 
something like:

irb(main):052:0> giveRating(["good plot", "bad writing"])
My rating for the movie is: good plot, bad writing
nil
irb(main):053:0> giveRating({"acting" => 5, "music" => "awful"})
My rating for the movie is: music => awful, acting => 5
nil

Any thoughts, comments, harsh criticism?

Ben