-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimmutable-base.rb
49 lines (34 loc) · 885 Bytes
/
immutable-base.rb
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 AbstractPerson
attr_accessor :name, :address
def initialize name, address
@name = name
@address = address
end
end
class Address
attr_accessor :line1, :line2, :line3
def initialize line1, line2, line3
@line1 = line1
@line2 = line2
@line3 = line3
end
end
class MutablePerson < AbstractPerson
# additional behaviour here...
end
class ImmutablePerson < AbstractPerson
def initialize name, address
super name, address
self.freeze
@address.freeze
end
def address
return @address.clone
end
end
address = Address.new("Foo Street", "Bar Town", "Test County")
person1 = MutablePerson.new("Foo McBar", address)
person1.address.line1 = "Bar Street"
puts person1.address.line1 # "Bar Street"
person2 = ImmutablePerson.new("Bar McFoo", address)
person2.address.line1 = "Bar Street" # error: can't modify frozen