-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfoo.rb
More file actions
66 lines (44 loc) · 1.02 KB
/
foo.rb
File metadata and controls
66 lines (44 loc) · 1.02 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# the following is intentionallly written badly for illustrative purposes
# you shouldn't have methods with the same name as
# the methods created by attr_accessor...
class Foo
attr_accessor :a, :b, :c, :cc
def initialize
@a,@b=0,0
@c=@a+@b
@cc=99
end
def cc
@a+@b
end
#this overwrites the attr_accessor
# be careful of this kind of thing because the inside is not what the outside can see .....
end
class Goo
def initialize
@a,@b=0,0
@c=@a+@b
@cc=99
end
def cc
@a+@b
end
attr_accessor :a, :b, :c, :cc # since this is called last and creates a new method cc, our method cc is overwritten
end
## test it
p f=Foo.new
#<Foo:0x000001008707e8 @b=0, @a=0, @c=0, @cc=99>
p g=Goo.new
#<Goo:0x00000100870658 @b=0, @a=0, @c=0, @cc=99>
f.a, g.a= 2, 2
p f.cc, g.cc
# 2
# 99
f.cc, g.cc= 55,55
p f.cc, g.cc
# 2
# 55
p f
#<Foo:0x000001008707e8 @b=0, @a=2, @c=0, @cc=55>
p g
#<Goo:0x00000100870658 @b=0, @a=2, @c=0, @cc=55>