Reputation: 199225
I have this small snipped of code.
I don't know ruby and I think this is a great opportunity to apply it.
I want to print all the lines in file e
which are not in file c
. Each line is a number.
This is what I've got:
e = File.new('e').readlines
c = File.new('c').readlines
x = e.collect do |item|
c.include?( item ) ? "" : item
end
p x.sort
The problem is that both file may have empty spaces and for that reason the same number may not be considered as such. ( eg. "1234 " is different from " 1234 " )
What do I need in my code to fix it? I've tried c.include?(item.strip)
.. .but doesn't seems to work.
Upvotes: 2
Views: 279
Reputation: 8125
Two things:
File.readlines("e").map(&:to_i) - File.readlines("c").map(&:to_i)
Upvotes: 3
Reputation: 35914
Perhaps doing the strip
when you do the readlines
would help, i.e.
e = File.readlines('e').map{|x| x.strip}
c = File.readlines('c').map{|x| x.strip}
Then you could use collect
as you did, or perhaps select
if you don't want the empty strings:
x = e.select{|i| !c.include?(i)}
Edit: or as Benno suggests, use
x = e-c
Upvotes: 3
Reputation: 29468
You can convert the items to actual numbers. Also, you should be closing those files after reading from them. File.new opens but does not close. You can open it in a block to automatically close it. Try:
e = nil
c = nil
File.open('e'){|file|
e = file.readlines
e.map!{|x| x.to_i}
}
File.open('c'){|file|
c = file.readlines
c.map!{|x| x.to_i}
}
To create the arrays of numbers.
Upvotes: 1