bottles
bottles

Reputation: 379

Am I Understanding Objects in Ruby Correctly?

I feel this is fundamental to my understanding of Ruby and object-oriented programming in general, so I'm asking this fairly simplistic question here at the risk of looking foolish. I've been toying around with irb. I've created my first ever 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 the combination of class Person and the attributes I've defined for that class?

Upvotes: 4

Views: 134

Answers (3)

Andrew Grimm
Andrew Grimm

Reputation: 81570

Strings are also objects, so after you've done

person_instance.firstname = "Bob"

then person_instance.firstname refers to a string object. So 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

Upvotes: 0

rb512
rb512

Reputation: 6948

You are right. Everything in ruby is an object. So when you create a new class 'person' it itself is an object of type class.

Upvotes: 0

phs
phs

Reputation: 11061

Your object is the result of running Person.new, which you've captured in person_instance.

In ruby, attributes don't actually exist until they are first written, so before person_instance.firstname = "Bob", your instance has no attributes. After executing this statement it has a @firstname attribute, but no others.

Upvotes: 6

Related Questions