You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby如何按对应行拼接合并两个文本文件的内容

Ruby按行拼接两个文件内容的代码修改方案

问题原因

  • File.readlines 读取的每行内容默认携带末尾的换行符\n,直接拼接会导致两个内容分行展示,出现上下拼接的不符合预期结果
  • 原代码使用空格作为拼接符号,和需求要求的|分隔符不符

修改后代码

优先推荐支持chomp参数的写法(Ruby 2.4及以上版本支持):

# 读取文件时直接去除每行末尾的换行符
f1 = File.readlines('./file1.txt', chomp: true)
f2 = File.readlines('./file2.txt', chomp: true)

File.open('result.txt', 'w') do |output_file|
  # zip方法自动配对两个数组的对应元素,不需要手动处理索引
  f1.zip(f2) do |line1, line2|
    # 兼容f2比f1行数少的场景,避免nil拼接报错
    next if line2.nil?
    output_file.puts "#{line1}|#{line2}"
  end
end

如果使用低版本Ruby,可手动处理换行符:

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|
    next unless f2[i]
    output_file.puts "#{elem}|#{f2[i]}"
  end
end

内容的提问来源于stack exchange,提问作者kh deep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 23:54:04