-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_variable.rb
More file actions
35 lines (29 loc) · 1.19 KB
/
Copy pathclass_variable.rb
File metadata and controls
35 lines (29 loc) · 1.19 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
# Class variable
# Class variables are shared among all instances and subclasses of a class and the class itself.
# They are defined using `@@` and can be accessed and modified by both class methods and instance methods.
# class variables are often used to store data that is common to all instances of a class,
# such as a count of how many instances have been created or a shared configuration setting.
class Bicycle
# class variable to keep track of the number of Bicycle instances created.
@@count = 0
# in every instance of Bicycle that is created, the initialize method increments the @@count variable by 1,
# so that we can keep track of how many Bicycle instances have been created.
def initialize
@@count += 1
end
# we can count the number of Bicycle instances created by calling the instance method `count`,
# which returns the value of the class variable @@count.
def count
@@count
end
# we can also count the number of Bicycle instances created by calling the class method `count`,
# which returns the value of the class variable @@count.
def self.count
@@count
end
end
b1 = Bicycle.new
Bicycle.new
Bicycle.new
p Bicycle.count # Output: 3
p b1.count # Output: 3