Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ruby to Find Common Lines in X files

Tags:

matching

ruby

Right now I have 3 files, but I'd like to do this in a way that I can add more later. Each file is a list of IDs, like this.

174535945 174538045 160515924 81712260 25241494

I'd like the output to be the items that appear in list 1 and list 2, list 2 and list 3, and those that occur in list 1 and list 2 and list 3.

Would the most ruby way to be create a hash with a key for each list, and then get all keys and test against all hashes, or is there a nice gem that would help with this?

Thanks,

like image 556
Peck Avatar asked May 31 '26 13:05

Peck


1 Answers

Use sets:

require 'set'

list_1 = open(filename_1).read.split.to_set
list_2 = open(filename_2).read.split.to_set
list_3 = open(filename_3).read.split.to_set

puts list_1 & list_2
puts list_2 & list_3
puts list_1 & list_2 & list_3
like image 76
Peter Avatar answered Jun 02 '26 05:06

Peter