Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby self in layman terms?

Tags:

ruby

When is Ruby self refering to the Object and when is self refering to the Ruby class? Explanations with examples would be great. Not getting my head around this.

like image 952
Imran Avatar asked Dec 28 '22 22:12

Imran


1 Answers

Classes are actually objects themselves. Lets say that I have a class Person, this is actually an instance of Class. So you can have self refer to an instance of Article, or you can have self refer to the instance of the class, Article.

In the most simple example I can think of:

class Person
  def initialize
    p "Info about Person Instance"
    p self
    p self.class
  end

  p "Info about Person Class"
  p self
  p self.class
end


person = Person.new

It prints:

"Info about Person Class"
Person
Class
"Info about Person Instance"
#<Person:0x0000010086cf58>
Person

To read more about about self, I highly recommend read this.

like image 168
Mike Lewis Avatar answered Jan 11 '23 15:01

Mike Lewis