Skip to content

Instantly share code, notes, and snippets.

@oogali
Created April 18, 2012 02:44
Show Gist options
  • Save oogali/2410736 to your computer and use it in GitHub Desktop.
Save oogali/2410736 to your computer and use it in GitHub Desktop.
example on matching regex in a variable via case/when/end
#!/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