Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the 'case' statement in order to match multiple 'when' conditions

I am using Ruby on Rails 3 and I would like to use a case statement that even after matching a when statement can continue to checks other when statement until the last else.

For example

case var
when '1'
  if var2 == ...
    ...
  else
    ...
    puts "Don't make nothig but continue to check!"
    # Here I would like to continue to check if a 'when' statement will match 'var' until the 'else' case
  end
when '2'
  ...
...
else
  put "Yeee!"

end

Is it possible in Ruby? If so, how?

like image 873
user502052 Avatar asked Oct 12 '22 14:10

user502052


1 Answers

Most of the code I see coming from ruby is done with if elsif else but you can mimic switch logical expressions similar to other languages like this:

case var
when 1
  dosomething
when 2..3
  doSomethingElse
end

case
when var == 1
   doSomething
when var < 12
   doSomethingElse
end

This came from this SO Question. Like I said this is usually done with if elsif else in ruby such as:

if my_number == "1"
   #do stuff when equals 1
elsif my_number == "e"
   #same thing here
else
   #default, no case found
end 
like image 107
thenengah Avatar answered Oct 15 '22 10:10

thenengah