Regular Expressions in Case Statements

suggest change

You can test if a string matches several regular expressions using a switch statement.

Example

case "Ruby is #1!"
when /\APython/
    puts "Boooo."
when /\ARuby/
    puts "You are right."
else 
    puts "Sorry, I didn't understand that."
end

This works because case statements are checked for equality using the === operator, not the == operator. When a regex is on the left hand side of a comparison using ===, it will test a string to see if it matches.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents