Do I understand objects correctly in Ruby?

I believe this is fundamental to my understanding of Ruby and object-oriented programming in general, so I am asking this rather simplified question here, at the risk of looking stupid. I practiced with irb. I created my first class:

$ irb ruby-1.9.2-p290 :001 > class Person ruby-1.9.2-p290 :002?> attr_accessor :firstname, :lastname, :gender ruby-1.9.2-p290 :003?> end => nil ruby-1.9.2-p290 :004 > person_instance = Person.new => #<Person:0x007f9b7a9a0f70> ruby-1.9.2-p290 :005 > person_instance.firstname = "Bob" => "Bob" ruby-1.9.2-p290 :006 > person_instance.lastname = "Dylan" => "Dylan" ruby-1.9.2-p290 :007 > person_instance.gender = "male" => "male" 

So Person.new is my object, right? Or is my object a combination of class Person and the attributes that I defined for this class?

+4
source share
3 answers

Your object is the result of running Person.new , which you committed to person_instance .

In ruby, attributes do not actually exist until they are written for the first time, so before your person_instance.firstname = "Bob" your instance has no attributes. After executing this statement, it has the @firstname attribute, but not others.

+6
source

You're right. Everything in a ruby ​​is an object. Therefore, when you create a new class "man", he himself is an object of a class type.

0
source

Strings are also objects, so after you have done

 person_instance.firstname = "Bob" 

then person_instance.firstname refers to the string object. Therefore you can call

 # Returns String, indicating that the object returned by # person_instance.firstname is an instance of the String class. person_instance.firstname.class # Returns a not very informative number, but indicates that it is its own object person_instance.firstname.object_id 
0
source

All Articles