?

Log in

No account? Create an account
wshaffer
Adventures in Ruby: Gets not getting from stdin 
4th-Nov-2014 12:09 pm
bannakaffalatta, short
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 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.
Comments 
4th-Nov-2014 08:12 pm (UTC)
Perl has similar shortcuts for "read from files or stdin". Useful for quick one-off code, but can get confusing if you don't expect it.
4th-Nov-2014 11:36 pm (UTC)
It's probably one of those features that Ruby borrowed from Perl. Now that I know about it, I can see that it could come in quite handy, but it really caught me by surprise.
This page was loaded Nov 21st 2017, 2:25 am GMT.