Reputation: 187
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
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
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
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