unless =~ vs. ! =~

M

Marco Lazzeri

Hi!

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

next unless line =~ /=/

next if !line =~ /=/


Thanks,
Marco
 
M

Marco Lazzeri

Marco said:
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
 
W

William Crawford

Marco said:
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?
 
A

ara.t.howard

Hi!

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

next unless line =~ /=/

next if !line =~ /=/


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
 
R

Robert Klemme

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

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
 
C

Chad Perrin

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

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

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

/me stirs the pot a little.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,210
Messages
2,571,091
Members
47,692
Latest member
RolandRose

Latest Threads

Top