2

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.

1
  • This worked for me, ruby quicksort.rb < unsorted.txt Commented Jun 24, 2019 at 5:49

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

For arguments, use argv

ARGV.each do|file|
file
end

Then you can read contents of the file :

f = File.open(file, File::RDONLY)

Comments

2

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

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.