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.
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.
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.
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...
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With