Today's little Ruby conundrum that I'm noting for future reference: I've written a script that takes two CSV files, File A and File B, and removes entries from File A if they match up with certain things in File B. The script is invoked at the command line by typing
Having done this, I wanted to ask the user if they wanted to do additional filtering based on an additional criterion, so I added the following.
To my bewilderment, when I ran the script, it blew through that
I did eventually find the answer on Stack Overflow, but it was obscure enough that I'm blogging here for my own reference. Basically, it turns out that
To make
I assume that this isn't more widely documented because few people mix command-line arguments and interactive input in a single script. In fact, I'm not sure I should really be mixing command-line arguments and interactive input in a single script, but I'm already asking the user to type a hell of a lot at the command-line, and this seems like a reasonable hack to get something useable while I decide on a better way to handle this.
ruby my_script.rb filenameA filenameB. Having done this, I wanted to ask the user if they wanted to do additional filtering based on an additional criterion, so I added the following.
puts "If you want to do additional filtering, enter a filter string. Otherwise press Enter."
response = gets.chomp!
To my bewilderment, when I ran the script, it blew through that
gets statement without pausing for input and proceeded to filter the output in an unexpected way. I did eventually find the answer on Stack Overflow, but it was obscure enough that I'm blogging here for my own reference. Basically, it turns out that
gets doesn't read from standard input by default. It reads from ARGF, which is an array containing the filenames passed to the script as command line arguments. So, my script as written grabbed the first line of File A and filtered based on that. To make
gets grab input from standard input, I should have used $stdin.gets. I assume that this isn't more widely documented because few people mix command-line arguments and interactive input in a single script. In fact, I'm not sure I should really be mixing command-line arguments and interactive input in a single script, but I'm already asking the user to type a hell of a lot at the command-line, and this seems like a reasonable hack to get something useable while I decide on a better way to handle this.
(no subject)
Date: 2014-11-04 08:12 pm (UTC)(no subject)
Date: 2014-11-04 11:36 pm (UTC)