1

im new to ruby but i would like to create a case block which uses arrays (or something similar as the argument)

here is what i have in mind

thirty_one_days_month = [1, 3, 5, 7, 8, 10, 12]
thirty_days_month = [4, 6, 9, 11]

case month
when thirty_one_days_month #instead of 1, 3, 5, 7, 8, 10, 12
#code
when thirty_days_month #instead 4, 6, 9, 11
#code

i know this code wont work but is this at all possible?

Xitcod13
  • 5,949
  • 9
  • 40
  • 81
  • Related: http://stackoverflow.com/questions/5781639/passing-multiple-error-classes-to-rubys-rescue-clause-in-a-dry-fashion/5782805#5782805 – sawa Mar 31 '14 at 23:52

2 Answers2

4

Use the splat operator:

case month
when *thirty_one_days_month
  #code
when *thirty_days_month
  #code
end

Anyway, that's how I'd write it:

days_by_month = {1 => 31, 2 => 28, ...}

case days_by_month[month]
when 31
  # code
when 30
  # code
end
tokland
  • 66,169
  • 13
  • 144
  • 170
1

You can use a case statement like this:

case
when thirty_one_days_month.include?(month)
    puts "31 day month"
when thirty_days_month.include?(month)
    puts "30 day month"
else
    puts "February"
end
khagler
  • 3,996
  • 29
  • 40