如何将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
catwith a pipe:cat my_file.csv | ./my_ruby_script.rb - Using input redirection (this is more efficient and avoids spawning an extra
catprocess):./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_printgem is installed (rungem install awesome_printif 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
相关产品推荐
相关产品推荐

