Which methods does "puts" invoke?

  • Thread starter Iñaki Baz Castillo
  • Start date
I

Iñaki Baz Castillo

Hi, if I redefine "to_s" or "inspect" methods in String class I still get t=
he=20
original output when doing:

puts string

Which String@method is invoked when executing "puts"?

Thanks.

=2D-=20
I=C3=B1aki Baz Castillo <[email protected]>
 
E

Eric Jacoboni

Iñaki Baz Castillo said:
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)

to_s called
=> nil
 
L

Lyle Johnson

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

=A0puts 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.
 
I

Iñaki Baz Castillo

El Lunes 30 Marzo 2009, Eric Jacoboni escribi=F3:
to_s (inspect is called by p)


=3D> nil




=3D> nil


to_s called
=3D> nil


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

=2D-------
class String
def to_s
"hiiiiiii"
end
end

# s=3DString.new("qweqwe")
# puts s
qweqwe
nil
=2D----------

=BF?

=2D-=20
I=F1aki Baz Castillo <[email protected]>
 
E

Eric Jacoboni

--------
class String
def to_s
"hiiiiiii"
end
end

# s=String.new("qweqwe")
# puts s
qweqwe
nil
-----------

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

Rob Olson

Hi, if I redefine "to_s" or "inspect" methods in String class I still getthe
original output when doing:

  puts string

Which String@method is invoked when executing "puts"?

Thanks.


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."
 
B

Brian Candler

Eric said:
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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top