I need to pass a text file as an argument instead of opening it inside the code. The content of the text file should print on console. I have done the following code:
File.open("test_list.txt").each do |line|
puts line
end
Please advice.
On your shell, invoke the ruby
script followed by the name of the .txt
file, like this:
ruby foo.rb test_list.txt
The variable ARGV
will contain references to all the arguments you've passed when invoking the ruby
interpreter. In particular, ARGV[0] = "test_list.txt"
, so you can use this instead of hardcoding the name of the file:
File.open(ARGV[0]).each do |line|
puts line
end
On the other hand, if you want to pass the content of the file to your program, you can go with:
cat test_list.txt | ruby foo.rb
and in the program:
STDIN.each_line do |line|
puts line
end