Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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('|') }
over 4 years ago · Santiago Trujillo Report

0

.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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!