Profile

wshaffer: (Default)
wshaffer

September 2021

S M T W T F S
   123 4
56789 1011
12131415161718
19202122232425
2627282930  

Custom Text

Most Popular Tags

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.

(no subject)

Date: 2014-11-04 11:36 pm (UTC)
From: [identity profile] wshaffer.livejournal.com
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.

Expand Cut Tags

No cut tags

Style Credit