简体   繁体   中英

how to combine 2 file text with join line in ruby

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

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('|') }

.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM