hash - How to compare two text files with value in ruby -
i have 2 text file, , have 1 same field(pet). want combine 2 file , output new file contain 3 fields(owner pet buyer). code depends on if both file have same pet(name , number of pets) add name of buyer field of buyer in new file. should print out if 2 file have same filed of pet.
but code did not work want, need 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 result this:
owner pet buyer michael cat, dog sean, mark, tina mary cat, dog sean, mark, tina
my code looks this:
input_file_1 = argv[0] input_file_2 = argv[1] hash_1 = {} file.readlines(input_file_1, "\n").each |line| owner, pet = line.chomp.split("\t") hash_1[owner] = pet end hash_2 = {} file.readlines(input_file_2, "\n").each |line| buyer, pet = line.chomp.split("\t") hash_2[buyer] = pet end hash_1.each |key, value| if hash_2.has_value? value puts "#{key}\t#{value}\t#{hash_2[key]}" end end
i suggest use pet
key:
input_file_1 = argv[0] input_file_2 = argv[1] hash_1 = hash.new([]) file.readlines(input_file_1, "\n").each |line| owner, pet = line.chomp.split("\t") hash_1[pet] += [owner] end hash_2 = hash.new([]) file.readlines(input_file_2, "\n").each |line| buyer, pet = line.chomp.split("\t") hash_2[pet] += [buyer] end hash_1.each |pet, owners| if hash_2.include? pet owners.each |owner| puts "#{owner}\t#{pet}\t#{hash_2[pet].join(", ")}" end end end
Comments
Post a Comment