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
.
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
No. Case statements evaluate the first when
block whose target's ===
method evaluates to true
when passed the comparison, and stop there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With