Forum: Ruby Help me understand this code please.

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.
7f5165277d81a4483ced82e4714b5bf9?d=identicon&s=25 Michael Lee (michael_l96)
on 2016-09-24 15:23
If self refers to the object created by instantiating its current class.
Why does self in this case equal a?
We instantiated twice? We have 2 objects?
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2016-09-29 11:53
Your code is incomplete, and I don't quite understand all of your
questions.

I assume that the first class (where you did not provide the full code)
is the class Animal.

We have three instanciations.

First, a Zebra is instanciated and assigned to a.

Second, another Zebra is instanciated and assigned to b.

Then, the method + is invoked on a. Inside the method body, self is
bound to receiver, which is the object a. Hence. self.name means the
name of the Zebra a.

During the execution of +, a Animal is instantiated and returned as a
result of the + method.

This Animal is then passed to puts.
This topic is locked and can not be replied to.