Instance Variables


Collapse Content

Instance variables are available to the whole class and are created with @:

class Dog
  @name
end

@name isn't currently accessible from outside the class. Ruby uses a method named initialize to set up values when an object is created. (This is like Java's constructors.)

class Dog

    def initialize(name)
      @name = name
    end        

    #getter
    def name
        @name
    end

    def bark
        puts "Woof!"
    end
end

Note the method name above. This lets code outside the class get the value of @name.1

We can now create a Dog:

doggy = Dog.new("Max")  #creates new Dog named "Max"
puts doggy.name  #calls Dog's `name` method, which returns @name

This prints out:

Max


1. Ruby also provides shortcuts for creating methods to access and change variables; see Ruby Classes.

Challenge

Copy your simple Product class form before and make it useful:

  1. Inside your Product class, create an initialize method that takes in 2 parameters and assigns their values to 2 instance variables named @name and @description.
  2. Create 2 'getter' methods to return the value of @name and @description.
  3. Change your method to_s so it returns something more useful: the name of the product followed by the description. For example, a product named "Pencil" with a description "Writing implement" should return "Pencil Writing implement".

Need help? Click on the hints you need below.

Hint for #1

Hint for #2

Hint for #3

Challenge

Create a Product class as described above.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]