Lesson 14 of 15
Classes
Classes in Ruby
A class is a blueprint for objects. Define one with class and end:
class Dog
def initialize(name)
@name = name # instance variable
end
def bark
"#{@name} says: Woof!"
end
end
dog = Dog.new("Rex")
puts dog.bark # Rex says: Woof!
Instance Variables
Instance variables start with @ and are private by default. Use attr_reader, attr_writer, or attr_accessor to expose them:
class Person
attr_reader :name # creates a getter
attr_accessor :age # creates getter and setter
def initialize(name, age)
@name = name
@age = age
end
end
p = Person.new("Alice", 30)
puts p.name # Alice
p.age = 31
puts p.age # 31
to_s
Override to_s to control how an object is printed:
class Point
def initialize(x, y)
@x = x
@y = y
end
def to_s
"(#{@x}, #{@y})"
end
end
puts Point.new(3, 4) # (3, 4)
Scope Resolution Operator (::)
The :: operator accesses constants and methods inside a module or class. For example, Math::PI retrieves the PI constant from the built-in Math module. You'll see this pattern frequently with namespaced code.
Your Task
Create a Circle class with:
initialize(radius)— stores the radius as@radiusarea— returns(Math::PI * @radius ** 2).round(2)to_s— returns"Circle(radius=<radius>)"
Create Circle.new(5), print its string form and its area.
ruby.wasm loading...
Loading...
Click "Run" to execute your code.