Ruby on Rails Course 2009

Ruby: Classes

Class Definition

class SomeClass
  def some_method
  end
end

Instance Variables

class Person
  @name = "Bob"

  def greet
    "Welcome " + @name + "!"
  end

  def change_to_fred
    @name = "Fred"
  end
end

Usage

person = Person.new
puts person.greet # => "Welcome Bob!"
person.change_to_fred
puts person.greet # => "Welcome Fred!"

Instantiation

  • The .initialize method is called when a new instance is created.
  • Parameters passed to .new will be passed to the .initialize method.
class Person
  def initialize(name)
    @name = name
  end
end

person = Person.new("Joe")

Accessing Instance Variables

class Person
  def name
    @name
  end

  def name=(name)
    @name = name
  end
end

Attribute Accessors

The previous example could have been written like this:

class Person
  attr_accessor :name
end
  • attr_accessor will give you get/set functionality
  • attr_reader getter only
  • attr_writer setter only

Inheritance

  • Methods and variables can be inherited from another class.
  • No multiple inheritance!
class Person
  attr_accessor :name
end

class Employee < Person
  attr_accessor :position
end

Access Control

Default:

  • public methods are accessible by anyone

Others:

  • protected methods are accessible also to child objects
  • private methods are accessible only to the class that defines them

Example

class Person
  def name
    @name
  end

  protected
    def name=(name)
      @name = name
    end

  private
    def change_to_bob
      @name = "Bob"
    end
end