Classes
Create a class
initialize runs when you call new.
class User
def initialize(name)
@name = name
end
def label
"User: #{@name}"
end
end
u = User.new("Ada")
puts u.label
Attribute readers
Helpers expose instance variables cleanly.
class Course
attr_reader :title
attr_accessor :lessons
def initialize(title, lessons)
@title = title
@lessons = lessons
end
end
Class methods
Use self. for methods on the class itself.
def self.demo
Course.new("Ruby", 18)
end
Class tips
- Instance variables start with
@ - Prefer
attr_reader/attr_accessorover public@access - One class per file is a common pattern
- Inheritance uses
<
Comments
One comment per signed-in account. Comments are saved with this page’s URL.