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

如何将CSV通过管道传入Ruby脚本?求正确代码实现

How to Pipe a CSV File into a Ruby Script

First up, let's fix the command syntax—your current command my_file.csv | my_ruby_script.rb doesn't work because you're trying to pipe the filename itself, not the actual content of the CSV file. Here are two correct ways to pass the CSV data to your script:

  • Using cat with a pipe:
    cat my_file.csv | ./my_ruby_script.rb
    
  • Using input redirection (this is more efficient and avoids spawning an extra cat process):
    ./my_ruby_script.rb < my_file.csv
    

Next, make sure your Ruby script has execute permissions. Run this command once to mark it as executable:

chmod +x my_ruby_script.rb

Your Ruby code is actually almost right! Let's confirm it works with the fixed command. Here's the code again with a small robustness note:

#!/usr/bin/env ruby
require 'csv'
require 'awesome_print'

# Read input from STDIN and parse CSV with headers enabled
CSV.parse(STDIN.read, headers: true) do |row|
  ap row.to_hash
end

If it's still not running, check these common issues:

  • Ensure your CSV file has valid, properly formatted headers (no missing or malformed entries).
  • Make sure the awesome_print gem is installed (run gem install awesome_print if you haven't already).
  • Verify Ruby is installed and accessible in your system's PATH.

For testing, try using a simple sample CSV first to rule out formatting problems:

name,age,email
Alice,30,alice@example.com
Bob,25,bob@example.com

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:48:56