Classes and Modules
A class has an initialize constructor, instance variables starting with @, and attr_accessor for getters and setters. Inherit with <. Modules share methods using include.
Example
module Greets
def hello = "Hi, I am #{name}"
end
class Person
include Greets
attr_reader :name
def initialize(name) = @name = name
end
class Student < Person
attr_accessor :score
def initialize(name, score)
super(name)
@score = score
end
def to_s = "#{name}: #{score}"
end
s = Student.new("Ada", 70)
puts s, s.hello
s.score += 5
puts s.scoreResult
Ada: 70 Hi, I am Ada 75
Exercise
Auto create getters.
:nameQuiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.