Learning Ruby: Classes & Objects

ยท 2 minute read

Classes in ruby are first-class objects. Each is an instance of class Class

A class can be defined simply as:

class House
end

Classes ๐Ÿ”—

To make an instance of House

house_1 = House.new

We can set values to the House class, which will be inherited by every instance.

class House
  def initialize(color)
    @color = color
  end
end

house = House.new('blue')

We can access the instance values by creating getter methods in the class.

class House
  def initialize(color)
    @color = color
  end

  def color
    @color
  end

end

house = House.new('blue')
puts house.color

We can also set new values to instances by creating setter methods in the class.

class House
  def initialize(color)
    @color = color
  end

  def color
    @color
  end

  def color=(new_color)
    @color = new_color
  end

end

house = House.new('blue')
puts house.color

house.color = "red"
puts house.color

A better way to create the getter and setter without having to create new methods is to use attr_reader and attr_writer

class House
  attr_reader :color
  attr_writer :color

  def initialize(color)
    @color = color
  end

end

house = House.new('blue')
puts house.color

house.color = "red"
puts house.color

An even better way is to use attr_accessor to read and write

class House
  attr_accessor :color

  def initialize(color)
    @color = color
  end

end

house = House.new('blue')
puts house.color

house.color = "red"
puts house.color

A parent class can have its own variable, and they are denoted with two @@

class House
	@@count = 0
  def initialize(color)
    @color = color
  end

end

house = House.new('blue')

We can create a getter method for a parent class by using the self.[method name]

class House
	@@count = 0
	def self.count
		@@count
	end
  def initialize(color)
    @color = color
    @@count += 1
  end

end

house = House.new('blue')
puts house.count

๐Ÿ‘‰๐Ÿฝ See all notes in this series