Which methods does "puts" invoke?


#1

Hi, if I redefine “to_s” or “inspect” methods in String class I still
get the
original output when doing:

puts string

Which String@method is invoked when executing “puts”?

Thanks.


#2

Iñaki Baz C. removed_email_address@domain.invalid writes:

Hi, if I redefine “to_s” or “inspect” methods in String class I still get the
original output when doing:

puts string

Which String@method is invoked when executing “puts”?

to_s (inspect is called by p)

class Truc
end
=> nil

machin = Truc.new
=> #Truc:0x55604

puts machin
#Truc:0x55604
=> nil

class Truc
def to_s
“to_s called”
end
end
=> nil

puts machin
to_s called
=> nil


#3

On Mon, Mar 30, 2009 at 4:16 PM, Iñaki Baz C. removed_email_address@domain.invalid wrote:

Hi, if I redefine “to_s” or “inspect” methods in String class I still get the
original output when doing:

puts string

Which String@method is invoked when executing “puts”?

Based on my cursory inspection of the internals (in io.c) it doesn’t
appear that puts() is actually calling any of String’s methods, at
least not in any way that you can override them.


#4

El Lunes 30 Marzo 2009, Eric J.
escribió:> >> class Truc

#Truc:0x55604

puts machin

to_s called
=> nil

Well, I already tested it, and yes, it seems to work if you define to_s
method
in some custom class, but note the following:


class String
def to_s
“hiiiiiii”
end
end

s=String.new(“qweqwe”)

puts s

qweqwe
nil

¿?


#5

Iñaki Baz C. removed_email_address@domain.invalid writes:

nil

Oh yes, you’re right… puts doesn’t use to_s when called on a String.


#6

On Mar 30, 2:16 pm, Iñaki Baz C. removed_email_address@domain.invalid wrote:

Iñaki Baz C. removed_email_address@domain.invalid
From the rdoc of IO#puts (http://www.ruby-doc.org/core-1.8.7/classes/
IO.html#M000474) it states that puts “writes the given objects to ios
as with IO#print”. So puts calls print.

Further, the rdoc for IO#print ssays that objects passed to it “that
aren‘t strings will be converted by calling their to_s method.”


#7

Eric J. wrote:

Oh yes, you’re right… puts doesn’t use to_s when called on a String.

Nor on nil. (It prints “nil”, whereas nil.to_s is the empty string)