Reputation: 19031
I would like to do something like this in terminal
$ ruby quicksort.rb unsorted.txt
quicksort.rb
is the ruby file I would like to run unsorted.txt
is the input file that contains unsorted numbers. Is it possible to do something like this in ruby?
Thank you.
Upvotes: 2
Views: 1801
Reputation: 4808
While I do like solving stuff in Ruby I just want to point out:
> sort unsorted.txt > sorted.txt
if you have a decent (*nix) command line. But maybe you want to do more than just the sorting?
Upvotes: 1
Reputation: 3472
Just read from standard in, the shell can do this for you easily:
#!/usr/bin/env ruby
puts $stdin.read.reverse
Then use the "<" to forward the contents of the bar.txt file containing "foobar" to your program.
$ ruby foo.rb < bar.txt
raboof
Another solution that more matches what you want to do would be:
#!/usr/bin/env ruby
puts IO.read(ARGV[0]).reverse
running it:
$ ruby foo.rb bar.txt
raboof
Upvotes: 2
Reputation: 1517
For arguments, use argv
ARGV.each do|file|
file
end
Then you can read contents of the file :
f = File.open(file, File::RDONLY)
Upvotes: 2
Reputation: 25135
You can read the commandline arguments and do a file operation. to read arguments you can use
ARGV.each do|a|
puts "Argument: #{a}"
end
This way you can get the filename and get the content.
Upvotes: 3
Reputation: 104050
ARGF
makes this kind of task easy, almost as easy as Perl's <>
operator:
$ cat quicksort.rb
#!/usr/bin/ruby
ARGF.each do |line|
puts line
end
$ ruby quicksort.rb /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
...
You might like to bookmark this extremely helpful quick guide to Ruby IO.
Upvotes: 3