Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check ARGF is empty or not in Ruby

Tags:

ruby

I want to do with ARGF like this.

# 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 user input. I tried eof? or closed? doesn't help. Any ideas?

NOTE I was misunderstood ARGF. please see comments below.

like image 892
MarcJ Avatar asked Aug 18 '14 07:08

MarcJ


People also ask

How to check if a string is empty in Ruby?

Similarly, we can also use the length method to check for an empty string. If you want to check if a variable is nil or empty, you can check it like this in Ruby.

What happens if a block is not given in Ruby?

If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil). Is there any function opposite to empty? ? @RocketR you might want to checkout present? method. @dantastic #present? is Rails-only.

How to check if an array has an empty element?

To check if the array has an empty element, one of the many ways to do it is: arr.any? (&:blank?) blank? is not the same as empty?. Not sure what you want to do with it, but there are quite a few ways to skin this cat. More info would help narrow it down some...

Which array is not an empty array in Java?

Array arr1 is not an empty array. Array arr2 is not an empty array. Array arr3 is an empty array. In the above program, we created 3 arrays arr1, arr2, arr3.


2 Answers

Basically you'd examine #filename. One way to do this is:

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

And this is the 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

Another:

#!/usr/bin/env ruby
if not STDIN.tty? and not STDIN.closed?
  puts STDIN.read
else
  puts "No redirect."
end
like image 98
konsolebox Avatar answered Oct 18 '22 10:10

konsolebox


There might be a better way, but for me I needed to read the contents of a files being passed as arguments as well as having a files contents redirected 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
like image 43
Travis Avatar answered Oct 18 '22 11:10

Travis