Created
April 18, 2012 02:44
-
-
Save oogali/2410736 to your computer and use it in GitHub Desktop.
example on matching regex in a variable via case/when/end
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
line = "The quick brown fox jumped over the lazy dog" | |
r = { | |
:cat => /cat/, | |
:rabbit => /rabbit/, | |
:horse => /horse/, | |
:dog => /(\w+)\s+dog/ | |
} | |
case | |
when r[:cat].match(line) | |
puts "found a cat: #{line}" | |
when r[:rabbit].match(line) | |
puts "found a rabbit: #{line}" | |
when r[:horse].match(line) | |
puts "found a horse: #{line}" | |
when r[:dog].match(line) | |
puts "found a dog: #{line}" | |
puts "the word before dog is **#{$~[1]}**" | |
else | |
puts "did not find any matches: #{line}" | |
end | |
__END__ | |
roadrunner:~ oogali$ ./m.rb | |
found a dog: The quick brown fox jumped over the lazy dog | |
the word before dog is **lazy** |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment