-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_method.rb
More file actions
49 lines (39 loc) · 1.7 KB
/
Copy pathclass_method.rb
File metadata and controls
49 lines (39 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Class method
# class method is a method that is defined on the class itself, rather than on instances method of the class.
# Class methods are often used for utility functions or to create factory methods that return instances of the class.
# In Ruby, you can define a class method using the `self` keyword or by prefixing the method name with the class name.
class Vehicle
attr_reader :wheels, :passengers
def initialize(wheels, passengers)
@wheels = wheels
@passengers = passengers
end
# self keyword to define a class method that creates a new instance of the Vehicle class with specific attributes for a car.
# because we know it will create new instance of the class, we can use self.new() to create the instance. Or we can new() immediately without self because we are already in the class context.
def self.car
new(4, 5)
end
def self.bike
new(2, 2)
end
end
car = Vehicle.car
puts "Car has #{car.wheels} wheels and can carry #{car.passengers} passengers."
bike = Vehicle.bike
puts "Bike has #{bike.wheels} wheels and can carry #{bike.passengers} passengers."
# Alterenatively, you can also define class methods by prefixing the method name with the class name, like this:
class MathUtils
# notice that because we know that these methods are utility functions that don't depend on instance variables,
# we can combine them into a single class method definition block using `class << self`,
# which allows us to define multiple class methods without repeating the `self` keyword for each method.
class << self
def square(x)
x * x
end
def cube(x)
x * x * x
end
end
end
puts "Square of 3: #{MathUtils.square(3)}"
puts "Cube of 3: #{MathUtils.cube(3)}"