Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby remove the implicit break in Case statement? (How to make case like Switch)

x='bob'
case x
when "bob"
puts 'it stops here'
when 'bob'
puts 'but i want it to stop here'
end

Is there anyway to make case statements behave like the vanilla switch? So that it'll cycle through all the "when's" before breaking out? I'm surprised that ruby has it behave almost identically like a elsif.

like image 960
Mr. Demetrius Michael Avatar asked Dec 20 '22 21:12

Mr. Demetrius Michael


2 Answers

Michael,

While your example is a bit misleading ('bob' matches both 'bob' and "bob" so the first case would always match), you just can use simple if's like in if_test method below :

def case_test(x)                                                  
  puts case
  when x > 3
    "ct: #{x} is over 3"
  when x > 4
    "ct: #{x} is over 4"
  end   
end     

case_test(4)
case_test(5)

def if_test(x)
  puts "it: #{x} is over 3" if x > 3
  puts "it: #{x} is over 4" if x > 4
end     

if_test(4)
if_test(5)

This yields :

ct: 4 is over 3
ct: 5 is over 3
it: 4 is over 3
it: 5 is over 3
it: 5 is over 4

Note that you can also use multiple statements with when, which might help you or not depending on your real use case :

def many(x)              
  case x                 
  when 'alice','bob'     
    puts "I know #{x}"
  else·                  
    puts "I don't know #{x}"                                      
  end                    
end                      

many('alice')            
many('bob') 
many('eve')

Yields :

I know alice
I know bob
I don't know eve
like image 163
leucos Avatar answered Dec 23 '22 11:12

leucos


No. Case statements evaluate the first when block whose target's === method evaluates to true when passed the comparison, and stop there.

like image 37
Kerrick Avatar answered Dec 23 '22 11:12

Kerrick