With and without Song#to_s again

Hi all,

I posted a similar question a short time ago. But I
don't think the replies help me understand the
behaviors. So I post a short version( sorry if it
bothers you again).

I have the following script. I don't call Song#to_s in
my script but I can print all the attributes of a
song. Why is that?

Thanks,

Li

···

#########
class Song
  def initialize(name,artist,duration)
    @name=name
    @artist=artist
    @duration=duration
  end
  #attr_reader :name, :artist, :duration
  
  def to_s
   "#@name\t#@artist\t\t#@duration"
  end
end

s=Song.new('song1','author1','20')
puts s

######output

ruby ruby20c.rb

song1 author1 20

Exit code: 0

__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around

chen li wrote:

#########
class Song
  def initialize(name,artist,duration)
    @name=name
    @artist=artist
    @duration=duration
  end
  #attr_reader :name, :artist, :duration
  
  def to_s
   "#@name\t#@artist\t\t#@duration"
  end
end

s=Song.new('song1','author1','20')
puts s

######output

ruby ruby20c.rb

song1 author1 20

Exit code: 0

  As s is not a String (that is not s.is_a? String), it is converted
into string by puts. That exactly means your method to_s is called for
doing so.

  Vince

···

--
Vincent Fourmond, PhD student
http://vincent.fourmond.neuf.fr/

chen li wrote:

I have the following script. I don't call Song#to_s in
my script but I can print all the attributes of a
song. Why is that?

chen li, you can find this answer yourself.
1) Open a console and type:
ri Kernel.puts

2) See that it says that it's the same as $stdout.puts. Type:
ri IO.puts

3) See that it says that it does the same thing as print does. Type:
ri IO.print

4) See that it tells you that it calls the to_s method of any objects
that aren't strings.

you can find this answer yourself.

1) Open a console and type:
ri Kernel.puts

2) See that it says that it's the same as
$stdout.puts. Type:
ri IO.puts

3) See that it says that it does the same thing as
print does. Type:
ri IO.print

4) See that it tells you that it calls the to_s
method of any objects
that aren't strings.

Thank you for the detail explanation. Now I understand
why #to_s is called.

Li

···

--- Phrogz <gavin@refinery.com> wrote:

__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around