I'd probably write it something like this. It's an old-school thing:
(1..15).each do |number|
case
when (number % 3 == 0) && (number % 5 == 0)
puts "(#{ number }) Hello World"
when (number % 3 == 0)
puts "(#{ number }) Hello"
when (number % 5 == 0)
puts "(#{ number }) World"
else
puts number
end
end
# >> 1
# >> 2
# >> (3) Hello
# >> 4
# >> (5) World
# >> (6) Hello
# >> 7
# >> 8
# >> (9) Hello
# >> (10) World
# >> 11
# >> (12) Hello
# >> 13
# >> 14
# >> (15) Hello World
Here's how I'd really write it:
(1..15).each do |number|
val = case
when (number % 3 == 0) && (number % 5 == 0)
"Hello World"
when (number % 3 == 0)
"Hello"
when (number % 5 == 0)
"World"
else
number
end
puts val
end
This is cleaner and even more readable. While it's possible to use case 0
, the tests for each when
become less easily understood, which is a prime consideration when we write code. We write for at least two people, ourselves at the moment, and for whoever is maintaining it in the future. It needs to make sense at all times, so the more obvious and clean the code is, the faster it'll enter the brain when it's read in a couple years, reducing debugging time and the work-load on the future you.