Question

I have two text file, and they have one same field(pet). I want to combine two file and output a new file contain three fields(owner pet buyer). My code is mainly depends on if both file have the same pet(name and number of pets) than I will add the name of buyer to the field of buyer in the new file. It should print out only if the two file have same filed of pet.

But my code did not work as I want, need some help, thanks.

input_file_1 (.txt)

owner pet
Michael dog, cat
John pig, rabbit
Marry dog, cat

input_file_2 (.txt)

buyer pet
Sean cat, dog
Mark cat, dog
Joy dog, mouse
Tina cat, dog

I want the result to look like this:

owner pet buyer
Michael cat, dog Sean, Mark, Tina
Mary cat, dog Sean, Mark, Tina

My code looks like this:

input_file_1 = ARGV[0]
input_file_2 = ARGV[1]

hash_1 = {}
File.readlines(input_file_1, "\n").each do |line|
  owner, pet = line.chomp.split("\t")
  hash_1[owner] = pet
end

hash_2 = {}
File.readlines(input_file_2, "\n").each do |line|
  buyer, pet = line.chomp.split("\t")
  hash_2[buyer] = pet
end

hash_1.each do |key, value|
  if hash_2.has_value? value
    puts "#{key}\t#{value}\t#{hash_2[key]}"
  end
end
Was it helpful?

Solution

I would suggest you use the pet as key:

input_file_1 = ARGV[0]
input_file_2 = ARGV[1]

hash_1 = Hash.new([])
File.readlines(input_file_1, "\n").each do |line|
  owner, pet = line.chomp.split("\t")
  hash_1[pet] += [owner]
end

hash_2 = Hash.new([])
File.readlines(input_file_2, "\n").each do |line|
  buyer, pet = line.chomp.split("\t")
  hash_2[pet] += [buyer]
end

hash_1.each do |pet, owners|
  if hash_2.include? pet
    owners.each do |owner|
      puts "#{owner}\t#{pet}\t#{hash_2[pet].join(", ")}"
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top