Which methods does "puts" invoke?

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

puts string

Which [email protected] is invoked when executing “puts”?

Thanks.

Iñaki Baz C. [email protected] writes:

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

puts string

Which [email protected] 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

On Mon, Mar 30, 2009 at 4:16 PM, Iñaki Baz C. [email protected] wrote:

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

puts string

Which [email protected] 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.

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

¿?

Iñaki Baz C. [email protected] writes:

nil

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

On Mar 30, 2:16 pm, Iñaki Baz C. [email protected] wrote:

Iñaki Baz C. [email protected]
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.”

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)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs