Print vs puts behaviour for overloaded Array#to_s

Hi,
I’ve come across the following feature when using an overloaded to_s
method on an array. A simple example should explain it best :

class Foo
attr_reader :a, :b

def initialize
	@a=rand(10)
	@b=rand(10)
end

def to_s
	": #{a} #{b} :"
end

def diff
	a-b
end

end

test=Array.new
def test.to_s
str="“
self.each { |i| str+=”| #{i.diff.to_s} " }
str
end

(1…5).each { test << Foo.new }

puts test
puts test.to_s

print test,"\n"
print test.to_s,"\n"

This gives the following results:

: 3 2 :
: 3 6 :
: 0 1 :
: 9 4 :
: 7 1 :

1 | -3 | -1 | 5 | 6
1 | -3 | -1 | 5 | 6
1 | -3 | -1 | 5 | 6

So why does puts no pick up the overladed to_s function defined for
test, whereas print does?

Any help would be appreciated.

Steve

Any help would be appreciated.

Because test is an Array, and #puts do something different with an
Array. it make something like your method test#to_s (i.e. it execute a
loop)

Guy Decoux