Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda