-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample.rb
168 lines (125 loc) · 2.35 KB
/
example.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
### Example 1 ###
class Bob
def hey(drivel)
case
when taciturn?(drivel)
'Fine. Be that way!'
when forceful?(drivel)
'Woah, chill out!'
when curious?(drivel)
'Sure.'
else
'Whatever.'
end
end
private
def taciturn?(s)
s.strip.empty?
end
def curious?(s)
s.end_with?('?')
end
def forceful?(s)
s =~ /[A-Z]/ && s.upcase == s
end
end
### Example 2 ###
class Alice
def hey(drivel)
respond_to Phrase.new(drivel)
end
def respond_to(phrase)
case
when phrase.silent?
'Fine. Be that way!'
when phrase.loud?
'Woah, chill out!'
when phrase.quizzical?
'Sure.'
else
'Whatever.'
end
end
end
class Phrase
attr_reader :source
def initialize(drivel)
@source = drivel.to_s.strip
end
def quizzical?
source.end_with?('?')
end
def loud?
source =~ /[A-Z]/ && source.upcase == source
end
def silent?
source.empty?
end
end
### Example 3 ###
class Charlie
def hey(drivel)
answerer(drivel).reply
end
private
def answerer(drivel)
handlers.find {|answer| answer.handles?(drivel)}.new
end
def handlers
[AnswerSilence, AnswerShout, AnswerQuestion, AnswerDefault]
end
end
class AnswerSilence
def self.handles?(input)
input.strip.empty?
end
def reply
'Fine. Be that way!'
end
end
class AnswerQuestion
def self.handles?(input)
input.end_with?('?')
end
def reply
'Sure.'
end
end
class AnswerShout
def self.handles?(input)
input =~ /[A-Z]/ && input.upcase == input
end
def reply
'Woah, chill out!'
end
end
class AnswerDefault
def self.handles?(input)
true
end
def reply
'Whatever.'
end
end
### Example 4 ###
class David
Handler = Struct.new(:response, :pattern)
HANDLERS = {
:nothing => Handler.new("Fine. Be that way!", ->(i) { i.strip.empty? }),
:yell => Handler.new("Woah, chill out!", ->(i) { i.eql?(i.upcase) && i =~ /[A-Z]/ }),
:question => Handler.new("Sure.", ->(i) { i.end_with?("?") }),
:statement => Handler.new("Whatever.", ->(i) { true })
}
def hey(input)
respond(select_handler(input))
end
def respond(handler)
handler.response
end
def select_handler(input)
handlers.values.find { |r| r.pattern.call(input) }
end
def handlers
HANDLERS
end
end