Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Why do I get warning "regex literal in condition" here?

Tags:

ruby

A simple Ruby program, which works well (using Ruby 2.0.0):

#!/usr/bin/ruby
while gets
    print if /foo/../bar/
end

However, Ruby also outputs the warning warning: regex literal in condition. It seems that Ruby considers my flip-flop-expression /foo/../bar/ as dangerous.

My question: Where lies the danger in this program? And: Can I turn off this warning (ideally only for this statement, keeping other warnings active)?

BTW, I found on the net several discussions of this kind of code, also mentioning the warning, but never found a good explanation why we get warned.

like image 243
user1934428 Avatar asked Mar 20 '15 10:03

user1934428


1 Answers

You can avoid the warning by using an explicit match:

while gets
  print if ~/foo/..~/bar/
end

Regexp#~ matches against $_.

I don't know why the warning is shown (to be honest, I wasn't even aware that Ruby matches regexp literals against $_ implicitly), but according to the parser's source code, it is shown unless you provide the -e option when invoking Ruby, i.e. passing the script as an argument:

$ ruby -e "while gets; print if /foo/../bar/ end"

I would avoid using $_ as an implicit parameter and instead use something like:

while line = gets
  print line if line=~/foo/..line=~/bar/
end
like image 81
Stefan Avatar answered Sep 23 '22 20:09

Stefan