Ruby Objects

This section introduces Ruby's object-oriented programming model, including instances, methods, parameters, and memory management (instances and references). Later sections cover classes and modules and further topics.

Ref: WGR Chapter 2. Objects, methods, and local variables

Note: Following WGR's lead, in this section we define methods on instances (not on classes), to keep the lessons simple.

What is an object?

What is an object?

The Linguistic Metaphor for Objects

One way to think about objects:

Objects are things that can be described and can do things, or...

Objects vs. Classes

Creating an object

cookie = Object.new

Creating an object literally

fruit = "apple"

References and Instances

Stack Heap
fruit -> "apple"

Literals create instances

fruit = "apple"
dessert = "apple"
Stack Heap
fruit -> "apple"
dessert -> "apple"

References are independent of instances

fruit = "apple"
dessert = fruit
fruit = "banana"
dessert = fruit

What are the values of fruit and dessert after each line?

Object Identity

How can you tell if two references point to the same instance?

fruit = "apple"
dessert = "apple"
>> fruit.object_id
=> 2165091560
>> dessert.object_id
=> 2165084200

Ref. WGR Ch.2, Section 2.3.1

Object Equality

Note that .equal? is not guaranteed since bizarrely, some objects override .equal? to do something else. If you really want to know if two variables reference the same instance, compare their object_ids.

Garbage Collection

fruit = "apple"
fruit = "banana"

Side effects

friend = "Alice"
teacher = friend
friend.upcase!
teacher
=> "ALICE"

Behavior

Defining methods

cookie = Object.new

def cookie.bake
  puts "the oven is nice and warm"
end

Invoking methods

Behavior comes from messages and methods.

cookie.bake

prints I'm a cookie to the console

Method Definition Schematic

method definition

Ref. The Well-Grounded Rubyist PDF, Fig. 2.1

The methods method

>> cookie.methods
=> [:nil?, :===, :=~, :!~, :eql?, ...]
>> cookie.methods(false)
=> [:bake]

also useful: cookie.methods.sort, cookie.methods.grep(/age/)

>> cookie = Object.new
=> #<Object:0x007f86e485c3a8>
>> cookie.methods(false)
=> []
>> def cookie.bake; puts "hi"; end
=> nil
>> cookie.methods(false)
=> [:bake]

>> "goo".methods.grep(/sub/)
=> [:sub, :gsub, :sub!, :gsub!]

The respond_to? method

if cookie.respond_to? :bake
  cookie.bake
else
  puts "cookie is unbakable"
end

Note: Usually you don't use respond_to because of duck typing.

State

Instance variables are stored in the object

    def cookie.add_chips(num_chips)
      @chips = num_chips
    end

    def cookie.yummy?
      @chips > 100
    end

    cookie.add_chips(500)
    cookie.yummy?   #=> true

Self

Self Example

def cookie.yummy?
  @chips > 100
end

def cookie.add_chips(num_chips = 10)
  @chips 
  @chips += num_chips
end

def cookie.yummify
  add_chips until yummy?
end

 Previous Lesson Next Lesson 

Outline

[menu]

/