tags:

views:

70

answers:

3

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.

+2  A: 

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
Nate Kohl
Actually, x = e - c should work as well
Benno
e-c? .. nice ...
OscarRyz
+1  A: 

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.

bobDevil
+2  A: 

Two things:

  • you can use the minus operator for sets
  • why not convert to integers if each line is an integer?

  File.readlines("e").collect{|l| l.to_i} - File.readlines("c").collect{|l| l.to_i}
klochner