Instance Variables


Premium Content - Free Preview

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.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us