-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefining_equality_method.rb
More file actions
34 lines (28 loc) · 1.17 KB
/
Copy pathdefining_equality_method.rb
File metadata and controls
34 lines (28 loc) · 1.17 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
# Defining equality method
# In Ruby, you can define an equality method (==) for a class to specify how instances of that class should be compared for equality.
# This is typically done by overriding the `==` method in your class
class IceCream
attr_reader :flavor, :scoops
def initialize(flavor, scoops)
@flavor = flavor
@scoops = scoops
end
# Define the equality method
def ==(other)
# check if the other object is an instance of IceCream and compare their attributes
# if the other object is an instance of IceCream and has the same flavor and number of scoops, we consider them equal
if other.is_a?(IceCream) && flavor == other.flavor && scoops == other.scoops
true
else
false
end
# alternative in one line
# other.is_a?(IceCream) && flavor == other.flavor && scoops == other.scoops
end
end
ice_cream1 = IceCream.new("Vanilla", 2)
ice_cream2 = IceCream.new("Vanilla", 2)
ice_cream3 = IceCream.new("Chocolate", 3)
puts ice_cream1 == ice_cream2 # Output: true (same flavor and scoops)
puts ice_cream1 == ice_cream3 # Output: false (different flavor and scoops)
puts ice_cream1 == "Not an IceCream" # Output: false (different class)