bev
bev

Reputation: 187

Ruby: if statement using regexp and boolean operator

I'm learning Ruby and have failed to make a compound 'if' statement work. Here's my code (hopefully self explanatory)

commentline = Regexp.new('^;;') 
blankline = Regexp.new('^(\s*)$')

if (line !~ commentline || line !~ blankline)
  puts line
end

the variable 'line' is gotten from reading the following file:

;; alias filename backupDir

Prog_i  Prog_i.rb ./store
Prog_ii Prog_ii.rb ./store

This fails and I'm not sure why. Basically I want the comment lines and blank lines to be ignored during the processing of the lines in the file. Thanks for your help.

Upvotes: 1

Views: 285

Answers (3)

ratchet freak
ratchet freak

Reputation: 48196

you need to use an AND

basically you want not (blank or comment) which turns into not blank and not comment after applying DeMorgan

if (line !~ commentline && line !~ blankline)
  puts line
end

or

unless(line ~= commentline || line ~= blankline)
  puts line
end

depending on which you find more readable

Upvotes: 6

akuhn
akuhn

Reputation: 27793

You can write this much more terse, as

puts DATA.readlines.reject{|each|each =~ /^;;|^\s*$/}

__END__
;; alias filename backupDir

Prog_i  Prog_i.rb ./store
Prog_ii Prog_ii.rb ./store

Upvotes: 1

the Tin Man
the Tin Man

Reputation: 160551

This is your code:

commentline = Regexp.new('^;;') 
blankline = Regexp.new('^(\s*)$')

if (line !~ commentline || line !~ blankline)
  puts line
end

and how I'd write the same thing:

[
  ';; alias filename backupDir',
  '',
  'Prog_i  Prog_i.rb ./store',
  'Prog_ii Prog_ii.rb ./store'
].each do |line|

  puts line if (!line[/^(?:;;)?$/])

end

Which outputs:

;; alias filename backupDir
Prog_i  Prog_i.rb ./store
Prog_ii Prog_ii.rb ./store

Upvotes: 1

Related Questions