How do I get input to command line as ruby?

Asked 1 years ago, Updated 1 years ago, 122 views

How do I get input to command line as ruby?

> cat input.txt | myprog.rb
> myprog.rb < input.txt
> myprog.rb arg1 arg2 arg3 ...

I'm going to get stdin like this, but I'd like to know other ways than my code.

#!/usr/bin/env ruby

STDIN.read.split("\n").each do |a|
   puts a
end

ARGV.each do |b|
    puts b
end

command-line-argument directory file ruby

2022-09-22 22:08

1 Answers

#!/usr/bin/env ruby
puts ARGF.read

ARGF is a team related to the command-line or STDIN.

The factors passed to the script are stored in the ARGV array, and one factor is stored within an element.

$ cat test.rb
#!/usr/bin/env ruby

ARGF.each_with_index do |line, idx|
    print ARGF.filename, ":", idx, ";", line
end

#dline prints all lines to the forwarded file (including login).
ARGF.each do |line|
    puts line if line =~ /login/
end

$ $ sudo cat input.txt | ./test.rb
String in -:0;input.txt
I'm going to eat rice
$ $ ./test.rb input.txt
The string in input.txt:0;input.txt
input.txt:1; I eat rice
$ 


2022-09-22 22:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.