Command Line Applications in Ruby
Since Command Line Applications (CLAs) are the “little baby brother” of programming languages, understanding them is essential. They teach you how to use language to manage your computer.
A CLA in the context of Ruby is just a Ruby script that is run by the Ruby interpreter. The ruby command is used to launch the standard Ruby interpreter from the command line. Usually, options, the name of the program file, and any arguments come next. The standard input (STDIN), standard output (STDOUT), and standard error (STDERR) streams, along with command-line parameters, are the foundation of a traditional command-line program’s user interface.
Creating and Running a Basic Command Line Application
A single Ruby file that is executed by the interpreter is the most basic CLA.
Code Example 1: Simple Output Script
Your Ruby code would first be typed into a file, possibly called ex1.rb. Ruby files are best saved with the .rb extension.
File: ex1.rb |
puts "Hello World!" |
puts "I like typing this." |
You launch this file by calling the Ruby interpreter from your shell (PowerShell on Windows or Terminal on Mac OS X):
$ ruby ex1.rb
If everything went according to plan, the output ought to show up on the console right away.
Making a Script Self-Executable (Unix-like systems only)
Using a shebang line and adjusting permissions on Unix-like operating systems (like Linux or Mac OS X) allows you to make a script executable without having to type ruby each time.
Add the Shebang Line: Add an interpreter directive (shebang) as the very first line of the script to tell the operating system which program should run the file. | File: hello_world.rb | | :— | | #!/usr/bin/env ruby | | puts 'Hello World!' |
Grant Execute Permission: The script can be made executable by using the chmod command:
Execute Directly: The script can now be executed immediately with ./ if it is in your current directory:
Handling Command Line Arguments
In Ruby, the global array ARGV (Argument Variable), which is also reachable by the global synonym *, stores arguments entered on the command line as strings after the program file name.
- First,
ARGVholds the argument; second,ARGVholds the argument; and so forth. - The global variable
0contains the real name of the script that is on execution.
Code Example 2: Reading Arguments (Basic Arithmetic)
Two numbers are supplied as parameters to this script, which then prints the sum of those numbers.
File: add.rb |
number1 = ARGV |
number2 = ARGV |
puts number1.to_i + number2.to_i |
If this program is executed with arguments:
$ ruby add.rb 1 2
The output would be:
3
You can also read What Is RDoc In Ruby? The Official Ruby Documentation System
Comprehensive CLA Example: A Weather Tool
Argument handling, library requirements, and the self-executable pattern are all combined to create a professional CLA. The yahoo_weatherman gem, which needs to be installed with gem install yahoo_weatherman from the command line, is needed for this example.
Defining the Script Logic
To find the temperature based on a zip code, the program uses the weather(zip_code) method, which depends on the external yahoo_weatherman package.
File: weather |
#!/usr/bin/ruby |
require 'yahoo_weatherman' |
def weather(zip_code) |
client = Weatherman::Client.new |
client.lookup_by_location(zip_code).condition['temp'] |
end |
puts weather(ARGV) |
Note: The script is saved without the .rb extension, as the shebang line handles the interpreter specification.
Execution Steps (Unix-like systems)
After granting executable permissions, use the ZIP code argument to launch the script:
# Set executable permissions
$ chmod a+x weather
# Run the command line application (replace [ZIPCODE] with a real zip code)
$ ./weather [ZIPCODE]
Installing Globally (Optional)
To enable the command to be called from any directory without requiring the ./ prefix, you can build a symbolic link (sym-link) after testing:
sudo ln -s weather /usr/local/bin/weather
At this point, you can just type:
weather [ZIPCODE]
You can also read RubyGems Explained: Installing And Managing Ruby Libraries
Interacting with the Operating System
The shell or operating system is often used by Ruby apps. There are various ways that you can run OS commands straight from your Ruby script.
| Method | Description | Example (in Ruby script) | Output/Result |
| Backticks (“) | Executes the command in a subshell and returns the standard output as a string. | result = \ls“ | result holds a string list of files (e.g., "file1\nfile2\n") |
| Kernel.system | Executes the command in a subshell and returns true or false based on success/failure. | system 'echo "hello world"' | Prints "hello world" to the console; returns true |
| Kernel.exec | Replaces the current Ruby process with the specified executable. The script terminates immediately. | exec "echo", "*" | The Ruby script stops and the OS command runs. |
For more sophisticated control, libraries such as Open3 provide simultaneous access to the standard input, output, and error streams of the subprocess.
require 'open3'
# Captures output, error, and status from 'ls -l'
stdout, stderr, status = Open3.capture3('ls', '-l')
Essential Command Line Utilities
Working with CLAs will often need you to use the shell’s built-in directory manipulation commands, which Ruby writers routinely practice to expand their vocabulary.
| Command | Description | Example (Unix/OS X) |
| pwd | Print Working Directory (shows your current location) | $ pwd |
| ls | List directory (shows the contents of the current directory) | $ ls |
| cd | Change Directory (move to a new location) | $ cd temp/stuff |
| mkdir | Make Directory (create a new folder) | $ mkdir temp |
| rmdir | Remove Directory | $ rmdir john |
| cp | Copy a file or directory | $ cp neat.txt awesome.txt |
| rm | Remove (delete) a file | $ rm uncool.txt |
You can also read Ruby Domain Specific Language With Practical Code Examples
