Ruby Classes and Objects

Object-oriented programming in Ruby

Class Definition

class Person # define class
  def initialize(name, age) # constructor
    @name = name # instance variable
    @age = age
  end
  def greet # instance method
    puts "Hello, #{@name}"
  end
end

Creating Objects

person = Person.new("John", 30) # create instance
person.greet # call method

Attr Accessors

class Product
  attr_reader :name # getter only
  attr_writer :price # setter only
  attr_accessor :stock # getter and setter
  def initialize(name)
    @name = name
  end
end

Class Methods

class MyClass
  def self.class_method # class method
    puts "Class method"
  end
end
MyClass.class_method # call without instance

Inheritance

class Animal # parent class
  def eat
    puts "Eating"
  end
end
class Dog < Animal # inherit from Animal
  def bark
    puts "Woof!"
  end
end