Gavin Kistner
3/16/2007 9:33:00 PM
On Mar 14, 5:59 pm, "planetthoughtful" <planetthought...@gmail.com>
wrote:
> I'm a little confused about why the following two pieces of code seem
> to behave differently:
>
> if $val =~ /this/i
> puts "this"
> elseif $val =~ /that/i
> puts "that"
> elseif $val =~ /the other/i
> puts "the other"
> end
Thought I'd point out that Ruby's case statement is more powerful than
many other languages' switch statements:
%w| pthisic thatch mother armadillo |.each{ |val|
case val
when /this/i
puts "'#{val}' contains 'this'"
when /that/i
puts "'#{val}' contains 'that'"
when /other/i
puts "'#{val}' contains 'other'"
else
puts "'#{val}' does not contain 'this', 'that', or 'other'"
end
}
#=> 'pthisic' contains 'this'
#=> 'thatch' contains 'that'
#=> 'mother' contains 'other'
#=> 'armadillo' does not contain 'this', 'that', or 'other'
Also, note (as seen above) that the regexp you supplied as example
match substrings even inside words. Just in case you wanted exact case-
insenstive string matching, perhaps /\Athis\Z/i would be more
appropriate. If you wanted exact word matching, perhaps /\bthis\b/i
might be what you want.