-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotected_visibility.rb
More file actions
42 lines (32 loc) · 1.77 KB
/
Copy pathprotected_visibility.rb
File metadata and controls
42 lines (32 loc) · 1.77 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
# Protected visibility
# In Ruby, you can control the visibility of methods using the `protected` keyword.
# When a method is declared as protected, it can only be called by instances of the same class or subclasses.
# This means that you can call protected methods from within the class itself, and from instances of the same class or subclasses, but not from outside the class or on an instance of a different class.
class Car
def initialize(miles, age, name)
@base_value = 20_000
@age_depreciation = age * 1_000
@miles_depreciation = miles * 0.10
@value = @base_value - @age_depreciation - @miles_depreciation
@name = name
end
def compare_with(other_car)
self.value > other_car.value ? "#{name} is more valuable than #{other_car.name}" : "#{other_car.name} is more valuable than #{name}"
end
# the value and name methods are protected, which means that they can only be called by instances of the same class or subclasses.
# In this case, we can call the value and name methods from the compare_with method because it's defined in the same class.
# However, if we try to call the value or name methods from outside the class or on an instance of a different class, it will raise an error because they are protected methods.
protected
def value
@value
end
def name
@name
end
end
koenigsegg = Car.new(10_000, 2, "Koenigsegg")
bugatti = Car.new(50_000, 1, "Bugatti")
puts koenigsegg.compare_with(bugatti)
# if we try to call the value or name methods from outside the class or on an instance of a different class, it will raise an error because they are protected methods.
# puts koenigsegg.value # This will raise an error because value is a protected method.
# puts bugatti.name # This will raise an error because name is a protected method.