Unless =~ vs. ! =~

(Marco) #1

Hi!

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

  next unless line =~ /=/

  next if !line =~ /=/

Thanks,
Marco

···

--
Posted via http://www.ruby-forum.com/.

(Marco) #2

Marco Lazzeri 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

···

--
Posted via http://www.ruby-forum.com/.

(William Crawford) #3

Marco Lazzeri 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?

···

--
Posted via http://www.ruby-forum.com/.

(Ara.T.Howard) #4

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 Fri, 25 Aug 2006, Marco Lazzeri 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

--
to foster inner awareness, introspection, and reasoning is more efficient than
meditation and prayer.
- h.h. the 14th dalai lama

(Robert K.) #5

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 25.08.2006 16:37, Marco Lazzeri wrote:

Marco Lazzeri 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

(Chad Perrin) #6

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

/me stirs the pot a little.

···

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

Marco Lazzeri 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

--
CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ]
"The ability to quote is a serviceable
substitute for wit." - W. Somerset Maugham