3

I have this code

(1..50).each do |num|
    case num
      when num % 4 == 0, num % 6 == 0
        puts 'Cluck'
      when num % 4 == 0
        puts 'Cluck Cluck'
      when num % 5 == 0
        puts 'Cluck Cluck Cluck'
      else
        puts num
    end
end    

For some odd reason, instead of putting cluck cluck on the fourth line or cluck on the 24th line, it's just putting a list of 1 through 100. I can't figure out what's wrong with the switch statement. The first when using the comma or && doesn't change anything either (which I don't believe it should).

JoshEmory
  • 644
  • 6
  • 20

3 Answers3

3

Problems

case a when b

case a
when b

tests if a is equal to b.

In your case, a is a number (num) and b is a boolean (num % 4 == 0) so this never happens.

when b,c

Another problem is that

case
when b,c

tests if b or c.

If you want to check that num is divisible by 24, you need b and c.

Solution

Remove num from case and use logical and (&&) :

(1..100).each do |num|
  case
  when num % 4 == 0 && num % 6 == 0
  ## or just :
  # when num % 24 == 0
    puts 'Cluck'
  when num % 4 == 0
    puts 'Cluck Cluck'
  when num % 5 == 0
    puts 'Cluck Cluck Cluck'
  else
    puts num
  end
end
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
1

Oh well, Eric's answer is right on the money. I'd just add this as a reference -

It doesn’t end there though you can use a case statement without giving it a value to match against, which allows a case statement to mimic the behavior of an if statement, e.g.:

print "Enter a string: "
some_string = gets.chomp
case
when some_string.match(/\d/)
  puts 'String has numbers'
when some_string.match(/[a-zA-Z]/)
  puts 'String has letters'
else
  puts 'String has no numbers or letters'
end
Manish Giri
  • 3,562
  • 8
  • 45
  • 81
0

I read over this guide quick, and it seems to be that you're trying to use the case as an if statement, but you supplied a value to match against.

Because you gave num as the first argument of case, it's expecting to match against it. The problem is, your conditions evaluate to boolean values, and num is a number, so they'll never match, and the else condition will always be run.

Remove the num from the start of the case.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117