» Quick Introduction to Ruby » 2. Advanced » 2.1 Classes

Classes

You can define classes using the class keyword.

class Animal
  def initialize(name, age)
    @name = name
    @age = age
  end

  def speak
    puts "Hello, I am #{@name} and I am #{@age} years old."
  end
end

# Creating an instance of the Animal class
my_animal = Animal.new("Ruby", 3)

# Calling the speak method on the instance
my_animal.speak

The initialize method is a special method that gets called when you create a new instance of the class. It is used for setting up the initial state of the object.

Remember that in Ruby, instance variables (like @name and @age in this example) are prefixed with @ and are used to store state within an object.

Subclassing

In Ruby, subclassing is done with the < character.

class Person  
  def initialize(fname, lname)
   @fname = fname
   @lname = lname
  end

  def to_s
     "Person: #@fname #@lname"
  end
end
person = Person.new("Carl", "Max")
puts person # => Person: Carl Max


class Employee < Person
  def initialize(fname, lname, position)
    super(fname,lname)
    @position = position
  end

  def to_s
     super + ", #@position"
  end
end
employee = Employee.new("Carl", "Max", "CTO")

puts employee # => Person: Carl Max, CTO
puts employee.position # => CTO

Code Challenge

Create a Ruby class BankAccount that represents a simple bank account.

Loading...
> code result goes here
Prev
Next