Classes do not have to be in a separate file as you can see from the file below.
Let’s look at a class, then break it down.
class Student
# Class variable to keep track of the total number of students
@@total_students = 0
# Constructor method (called when a new object is created)
def initialize(name, age, grade)
@name = name # Instance variable for the student's name
@gpa = gpa # Instance variable for the student's gpa
@major = major # Instance variable for the student's major
@@total_students += 1
end
# Method to display student details
def display_info
puts "Name: #{@name}"
puts "GPA: #{@gpa}"
puts "Major: #{@major}"
end
# Class method to access the total number of students
def self.total_students
@@total_students
end
end
# Example usage:
student1 = Student.new("Alice", 3.25, "Business")
student2 = Student.new("Bob", 3.4, "Computer Science")
student1.display_info
student2.display_info
puts "Total students: #{Student.total_students}"
Class Definition
As with most languages, you use class
to define your class definition, and class names typically start with a capital letter.
As with conditions, and other blocks, the class definition ends with end
. This can be a little confusing since there are multiple ends associated with the internal methods. Therefore one might consider using a comment at the end of each end, to clearly delineate what it is in reference to.
Class Variables
Class level variables, if they exist in the class, are typically defined at the top of the class, shortly after defining the class.
# Class variable to keep track of the total number of students
@@total_students = 0
Constructor
Notice that you have a constructor, unlike Go. However, each language defines a constructor differently. Where Python uses init
and C/C++ and Java use the class name, Ruby uses initialize
. Like with Python, you use the def
keyword to define a method name, including the constructor.
# Constructor method (called when a new object is created)
def initialize(name, gpa, major)
@name = name # Instance variable for the student's name
@gpa = gpa # Instance variable for the student's gpa
@major = major # Instance variable for the student's grade
@@total_students += 1
end
Not only do we define the constructor, but also the class properties.
Methods
Class methods are after the constructor. A def
keyword is used to define them. Otherwise they are similar to any other function definition.
Classes in Ruby was originally found on Access 2 Learn