-
Notifications
You must be signed in to change notification settings - Fork 0
/
hfr-ch-8-object-references.rb
76 lines (61 loc) · 1.38 KB
/
hfr-ch-8-object-references.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#aliasing means referencing the same object
class CelestialBody
attr_accessor :name, :type
end
altair = CelestialBody.new
altair.name = "Altair"
altair.type = "Star"
polaris = altair
polaris.name = "Polaris"
vega = polaris
vega.name = "Vega"
p altair.name, polaris.name, vega.name
# how not to spin up a default object (due to aliasing)
default_body = CelestialBody.new
defauly_body_type = "Planet"
bodies = Hash.new(default_body)
bodies["Mars"].name = "Mars"
p bodies["Mars"]
bodies["Europa"].name = "Europa"
bodies["Europa"].type = "Moon"
p bodies["Europa"]
p bodies
#hash default block (generate new unique object upon first time accessing)
bodies = Hash.new do |hash, key|
body = CelestialBody.new
body.type = "Planet"
hash[key] = body
end
bodies["Mars"]
p bodies
bodies["Venus"]
p bodies
bodies["Mars"].type = "Moon"
p bodies
# code snippets for undersatnding default hash value / block behaviour
foods = Hash.new([])
foods['A'] << "Apple"
foods['A'] << "Banana"
foods['B'] << "Bacon"
foods['B'] << "Bread"
p foods['A']
p foods['B']
p foods
puts "*" * 50
foods = Hash.new { |h, k| [] }
foods['A'] << "Apple"
foods['A'] << "Banana"
foods['B'] << "Bacon"
foods['B'] << "Bread"
p foods['A']
p foods['B']
p foods
puts "*" * 50
foods = Hash.new { |h, k| h[k] = [] }
foods['A'] << "Apple"
foods['A'] << "Banana"
foods['B'] << "Bacon"
foods['B'] << "Bread"
p foods['A']
p foods['B']
p foods