-
Notifications
You must be signed in to change notification settings - Fork 0
/
about_variable_scope.rb
114 lines (86 loc) · 2.35 KB
/
about_variable_scope.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
require File.expand_path(File.dirname(__FILE__) + '/neo')
class AboutVariableScope < Neo::Koan
def bark
noise = "RUFF"
end
def test_noise_is_not_available_in_the_current_scope
assert_raise(___) do
noise
end
end
def test_we_can_get_noise_by_calling_method
assert_equal __, bark
end
inaccessible = "Outside our universe"
def test_defs_cannot_access_variables_outside_scope
# defined? does not return true or false
assert_equal __, defined? inaccesible
end
# ------------------------------------------------------
def test_blocks_can_access_variables_outside_scope
test = "Hi"
(1..2).each do
test = "Hey"
end
assert_equal __, test
end
def test_block_variables_cannot_be_accessed_outside_scope
(1..2).each do
x = 0
end
assert_equal __, defined? x
end
# ------------------------------------------------------
class Mouse
@@total = 0
# Class variables are prefixed with two '@' characters.
def initialize(n)
@name = n
# Instance variables are prefixed with one '@' character.
@@total += 1
end
def name
@name
end
def Mouse.count
@@total
end
end
def test_instance_variable
oscar = Mouse.new("Oscar")
assert_equal __, oscar.name
end
def test_class_variable
(1..9).each { |i| Mouse.new("#{i}") }
# Things may appear easier than they actually are.
assert_equal __, Mouse.count
end
# Meditate on the following:
# What is the difference between a class variable and instance variable?
# ------------------------------------------------------
$anywhere = "Anywhere"
# Global variables are prefixed with the '$' character.
def test_global_variables_can_be_accessed_from_any_scope
assert_equal __, $anywhere
end
def test_global_variables_can_be_changed_from_any_scope
# From within a method
$anywhere = "Here"
assert_equal __, $anywhere
end
def test_global_variables_retain_value_from_last_change
# What is $anywhere?
assert_equal __, $anywhere
end
def test_global_variables_can_be_changed_from_any_scope_2
# From within a block
(1..2).each do
$anywhere = "Hey"
end
assert_equal __, $anywhere
end
end
# THINK ABOUT IT:
#
# What will $anywhere be down here, outside of the scope of the
# AboutVariableScope class?