Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this switch statement not working? [duplicate]

Tags:

ruby

ruby-2.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).

like image 555
JoshEmory Avatar asked Jun 04 '26 21:06

JoshEmory


1 Answers

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
like image 173
Eric Duminil Avatar answered Jun 07 '26 20:06

Eric Duminil