I'm trying to understand how to use a conditional expression in a Ruby case/when statement. This code seems like it should work, but it only prints 1 through 100 inclusive, and never prints "Fizz", "Buzz" or "FizzBuzz".
#!/usr/bin/env ruby
(1..100).each do |n|
case n
when n % 3 == 0 && n % 5 == 0
puts "FizzBuzz"
when n % 3 == 0
puts "Fizz"
when n % 5 == 0
puts "Buzz"
else
puts n
end
end
I'm fairly sure I'm missing something obvious and stupid, but the documentation seems to indicate that this should work. Its very similar example was:
a = 2
case
when a == 1, a == 2
puts "a is one or two"
when a == 3
puts "a is three"
else
puts "I don't know what a is"
end
My Ruby version is:
ruby 2.1.6p336 (2015-04-13 revision 50298) [x86_64-linux]
And for completeness, the output:
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