Skip to content

Instantly share code, notes, and snippets.

@dgamboa
Created October 4, 2012 20:41
Show Gist options
  • Select an option

  • Save dgamboa/3836300 to your computer and use it in GitHub Desktop.

Select an option

Save dgamboa/3836300 to your computer and use it in GitHub Desktop.
In Ruby, is the attribute of an object an object?

###In Ruby, is the attribute of an object an object?

To illustrate, let's define a Book class where each book (or each instance of Book) has an author.

class Book
  attr_accessor :author

  def author
    @author
  end
end

We can create a new instance of Book and call it new_book by saying:

new_book = Book.new
=> #<Book:0x007f974c94f238>

We created a new instance of Book called new_book and it is stored as object #<Book:0x007f974c94f238>.

And to make sure that new_book is in fact an object, we can use the method #object_id, which returns an error if passed to anything other than an object.

new_book.object_id
=> 70143900809500

What happens if we ask new_book who its author is?

new_book.author
=> nil

We get nil because we haven't yet told new_book who authored him.

Let's tell it:

new_book.author = "Rudyard Kipling"
=> "Rudyard Kipling"

If we now ask new_book who its author is,

new_book.author
=> nil

It tells us that its author is "Rudyard Kipling".

Perfect! Now we can determine whether an attribute of an object is an object by passing #object_id to the author attribute of new_book. If it returns an object_id, we should conclude that attributes are objects.

new_book.author.object_id
=> 70143900735760

So there you have it. In Ruby the attribute of an object is indeed an object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment