Martin
Martin

Reputation: 217

How do I pass a text file or a string to a Ruby script and output the result in the command line?

As an exercise to learn Ruby, I would like to create a script that will be run from the terminal. It should accept as input either a string or a text file and it should output the result of various string parsing mechanisms that I will write myself.

To get me started, would you please translate this pseudo-code into proper Ruby for me?

  1. In terminal: ruby myscript.rb (either a string or a text file).
  2. In myscript.rb: Retrieve input. Set my_input to the input.
  3. Set my_output to the result of various_string_parsing_voodoo (done to my_input).
  4. puts my_output

I intend to actually write the code myself, but if someone could supply me with a skeleton .rb file to send in "Hello World" and get "[World] is pleased by your [hello]" or something equally inane that'd be a great help.

Upvotes: 3

Views: 1203

Answers (1)

ksol
ksol

Reputation: 12235

Here are some key pieces:

  • ARGV is an array containing the arguments you passed when running your script from command line.
  • the File class contains several utilies. For example, File.exists?(path) returns true if the path exists, and File.file?(path) returns true if the path exists and is a file (not a dir).

I think this may help you quite a bit.

Upvotes: 3

Related Questions