Ruby is a dynamic, open-source programming language praised for its elegance and readability. Mastering command-line interaction is crucial for any Ruby developer, regardless of experience level. This guide will walk you through executing Ruby files and commands directly from your console.
Table of Contents
- Installing Ruby on Your System
- Running Ruby Files from the Console
- Using the Interactive Ruby Shell (IRB)
- Working with Command-Line Arguments
Installing Ruby on Your System
The installation process depends on your operating system. Here’s a breakdown:
macOS
While macOS includes Ruby, it’s often an outdated version. For the latest version and robust package management, consider using rbenv or RVM. These tools allow you to manage multiple Ruby versions seamlessly.
Linux (e.g., Ubuntu)
Most Linux distributions offer Ruby packages through their package managers. On Ubuntu, use apt
:
sudo apt update
sudo apt install ruby ruby-dev
ruby-dev
provides development headers, essential for building Ruby extensions.
Windows
Download the Ruby installer from the official RubyInstaller website (https://rubyinstaller.org/). During installation, ensure you add Ruby to your system’s PATH environment variable to execute Ruby commands directly from the console.
Running Ruby Files from the Console
After installing Ruby, executing a Ruby program is simple. Assume you have a file named my_program.rb
:
puts "Hello, world!"
Open your console, navigate to the directory containing my_program.rb
, and run:
ruby my_program.rb
This instructs the Ruby interpreter to execute the script. The output will be:
Hello, world!
Using the Interactive Ruby Shell (IRB)
IRB allows you to execute single Ruby commands without creating files. Start IRB by typing:
irb
This opens an interactive environment where you can immediately see the results of your commands:
>> puts "Hello from IRB!"
Hello from IRB!
=> nil
>> 2 + 2
=> 4
>> exit
>>
is the IRB prompt. exit
closes the shell.
Working with Command-Line Arguments
Ruby scripts can accept command-line arguments accessible via the ARGV
array. Modify my_program.rb
:
name = ARGV[0]
puts "Hello, #{name}!"
Now, run the script with an argument:
ruby my_program.rb Alice
The output will be:
Hello, Alice!
This guide provides a solid foundation for working with Ruby from the command line. For more advanced techniques, refer to the official Ruby documentation.