Using 'case' with multiple conditions

Viewed 2840

I'm trying to write a case statement which looks at two conditions, like this:

roll1 = rand(1..6)
roll2 = rand(1..2)

result = case[roll1, roll2]
  when [1..3 && 1]
    "Low / Low"
  when [4..6 && 1]
    "High / Low"
  when [1..3 && 2]
    "Low / High"
  when [4..6 && 2]
    "JACKPOT!!"
end

puts result

I'd love to get this working. I'd prefer to understand why my example fails.

Edited to add:

Thanks for all the feedback! Inspired, I realized that combining the two case variables allows me to collapse them into a single value for a simple switch statement...

roll1 = rand(1..6)
roll2 = rand(1..2)

if roll2 == 1
  roll2 = 10
elsif roll2 == 2
  roll2 = 20
end

result = case(roll1 + roll2)
  when 11..13
    "Low / Low"
  when 14..16
    "High / Low"
  when 21..23
    "Low / High"
  when 24..26
    "JACKPOT!!"
end

puts result

While this solves my immediate problem, it doesn't advance my underlying knowledge -- it's a trifling insight compared to all the awesome feedback I've received. Sincere thanks!

5 Answers
Related