Announcement (2017-05-07): www.ruby-forum.com is now read-only since I
unfortunately do not have the time to support and maintain the forum any
more. Please see rubyonrails.org/community and ruby-lang.org/en/community
for other Rails- und Ruby-related community platforms.

My question regards the code below. I'm a new student to the Ruby
language/programming in general and I'm reading a book that supplied the
majority of the below code. Before I added the def to_s method the
below code would output
puts aSong.inspect as
"#<Song:0x401b4924 @duration=260, @artist=\"Fleck\",
@name=\"Bicylops\">"
and puts aSong as"
#<Song:0x401b499c>".
I understand this but as soon as I added the to_s method to the class
Song it automatically implemented it to both puts aSong.inspect and puts
aSong and displayed them as the to_s method that was created. This is
where I'm confused. I don't understand why it modified both of them
without being called on by a puts aSong.to_s call. If anyone could
explain this I would be greatful! God bless, Jesus loves you!
class Song
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
def to_s
"Song: #{@name}--#{@artist} (#{@duration})"
end
end
aSong = Song.new("Bocyclops", "Fleck", 260)
aSong.inspect
puts aSong.inspect
puts aSong

Joel Pearson wrote in post #1140083:
> If you override to_s, then you also override inspect. The solution is to> write your own inspect method every time you write your own to_s metthod.
Thanks for the reply I appreciate it! Bare with me but I'm confused.
1. How does override to_s also override inspect? I'm just trying to
understand. 2.I'm also confused about how creating a new method or
overriding an existing one automatically calls it?
Thanks again for the help!

Subject: Re: Help Please I'm Learning ;)
Date: lun 17 mar 14 02:13:01 +0100
Quoting Jameson Yount (lists@ruby-forum.com):
> Thanks for the reply I appreciate it! Bare with me but I'm confused.> 1. How does override to_s also override inspect? I'm just trying to> understand. 2.I'm also confused about how creating a new method or> overriding an existing one automatically calls it?
It is not that overriding to_s overrides inspect. What happens is that
the default inspect eventually invokes the object's #to_s method. This
happens in C (at least in MRI) - if you want to know exactly how, you
can study the source files object.c and string.c.
This is why, when you override to_s, the default behaviour of inspect
also changes.
Carlo