Unless =~ vs. ! =~

Hi!

Could someone please help me understanding why the next two lines of
code are different?

next unless line =~ /=/

next if !line =~ /=/

Thanks,
Marco

Marco L. wrote:

Could someone please help me understanding why the next two lines of
code are different?

next unless line =~ /=/

next if !line =~ /=/

I found out: it’s a operators precedence problem.

next unless line =~ /=/
next if !(line =~ /=/) # with parenthesis

Marco

Marco L. wrote:

Hi!

Could someone please help me understanding why the next two lines of
code are different?

next unless line =~ /=/

next if !line =~ /=/

Thanks,
Marco

I suspect !line =~ /=/ is not the same as !(line =~ /=/). Do you have
more of an example that people can run in IRB to verify?

On Fri, 25 Aug 2006, Marco L. wrote:

Thanks,
Marco

harp:~ > cat a.rb
require ‘yaml’

y “!‘foobar’” => (!‘foobar’)
y “!‘foobar’ =~ /barfoo/” => (!‘foobar’ =~ /barfoo/)
y “false =~ /barfoo/” => (false =~ /barfoo/)
y “‘foobar’ !~ /barfoo/” => (‘foobar’ !~ /barfoo/)

harp:~ > ruby a.rb
a.rb:3: warning: string literal in condition
a.rb:4: warning: string literal in condition

“!‘foobar’”: false
“!‘foobar’ =~ /barfoo/”: false
false =~ /barfoo/: false
“‘foobar’ !~ /barfoo/”: true

! binds more tightly that =~

-a

On 25.08.2006 16:37, Marco L. wrote:

next unless line =~ /=/
next if !(line =~ /=/) # with parenthesis

Note that you can also negate the match operator:

next if line !~ /=/

… or you use “not”

next if not line =~ /=/

My personal favorite here is your first one

next unless line =~ /=/

because it reads nice and clear.

Kind regards

robert

On Fri, Aug 25, 2006 at 11:37:25PM +0900, Marco L. wrote:

next unless line =~ /=/
next if !(line =~ /=/) # with parenthesis

Have you considered this alternative?
next if line !~ /=/

/me stirs the pot a little.