How to check if ARGF is empty or not in Ruby

I want to do with ARGF as follows.

 # file.rb if ARGF.??? puts ARGF.read else puts "no redirect." end $ echo "Hello world" | ruby file.rb Hello world $ ruby file.rb no redirect. 

I need to do without waiting for user input. Have I tried eof? or closed? did not help. Any ideas?

NOTE I was misunderstood by ARGF . see comments below.

+6
source share
2 answers

Basically you should learn #filename . One way to do this:

 if ARGF.filename != "-" puts ARGF.read else puts "no redirect." end 

And this is a more complete form:

 #!/usr/bin/env ruby if ARGF.filename != "-" or (not STDIN.tty? and not STDIN.closed?) puts ARGF.read else puts "No redirect." end 

Other:

 #!/usr/bin/env ruby if not STDIN.tty? and not STDIN.closed? puts STDIN.read else puts "No redirect." end 
+5
source

Maybe the best way, but for me, I needed to read the contents of the files passed as arguments, and also redirect the contents of the files to stdin.

my_executable

 #!/usr/bin/env ruby puts ARGF.pos.zero? 

Then

 $ my_executable file1.txt # passed as argument #=> true $ my_executable < file1.txt # redirected to stdin #=> true $ my_executable #=> false 
0
source

Source: https://habr.com/ru/post/973958/


All Articles