Home > Enterprise >  how to combine 2 file text with join line in ruby
how to combine 2 file text with join line in ruby

Time:11-22

Please help me how to do with this code. and what should i do with that code:

file1.txt       file2.txt
  aaa             111
  bbb             222
  ccc             333
  ddd             444

and the result just show like this

  aaa
  bbb
  ccc
  ddd
  111
  222
  333
  444

but what i want is

aaa|111
bbb|222
ccc|333
ddd|444

Here is my code

f1 = File.readlines('./file1.txt')
f2 = File.readlines('./file2.txt')

File.open('result.txt', 'w') do |output_file|
  f1.each_with_index do |elem, i|
    output_file.puts "#{elem} #{f2[i]}"
  end
end

CodePudding user response:

Instead of iterating on one array and looking up the second array by index, it is more elegant to zip the two arrays together. puts will, given an array, output each element in a separate row.

f1 = File.readlines('file1.txt', chomp: true)
f2 = File.readlines('file2.txt', chomp: true)

lines = f1.zip(f2).map { |items| items.join('|') }
puts lines

Or, using the new shorthand syntax, you could even say

lines = f1.zip(f2).map { _1.join('|') }

CodePudding user response:

.map(&:chomp)

f1 = File.readlines('./file1.txt').map(&:chomp)
f2 = File.readlines('./file2.txt').map(&:chomp)

File.open('result.txt', 'w') do |output_file|
  f1.each_with_index do |elem, i|
    output_file.puts "#{elem} #{f2[i]}"
  end
end

Result

aaa 111
bbb 222
ccc 333
ddd 444
  •  Tags:  
  • ruby
  • Related