-
Notifications
You must be signed in to change notification settings - Fork 0
/
greeting.rb
55 lines (45 loc) · 929 Bytes
/
greeting.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
def greet(*names)
names = normalize(names)
return say("my friend") if names.empty?
shouted, spoken = names.partition(&method(:shouted?))
[spoken, shouted]
.reject(&:empty?)
.map(&method(:greeting_for))
.join(" AND ")
end
def normalize(names)
names
.compact
.flat_map(&method(:decommafy))
end
def decommafy(name)
match = name.match(/\A"(.+)"\z/)
match ? match[1] : name.split(",").map(&:strip)
end
def greeting_for(names)
combined = combine(names)
names.all?(&method(:shouted?)) ? shout(combined) : say(combined)
end
def combine(names)
case names.size
when 1
names.first
when 2
names.join(" and ")
else
oxfordize(names)
end
end
def oxfordize(names)
last_name = names.pop
"#{names.join(", ")}, and #{last_name}"
end
def shouted?(name)
name == name.upcase
end
def shout(name)
"HELLO #{name.upcase}!"
end
def say(name)
"Hello, #{name}."
end