ruby Command Linux: Complete Guide to Running Ruby Scripts and Programs

August 25, 2025

The ruby command is a powerful tool for executing Ruby scripts and programs directly from the Linux command line. Whether you’re a beginner learning Ruby programming or an experienced developer managing Ruby applications, understanding how to effectively use the ruby command is essential for efficient development workflows.

What is the ruby Command?

The ruby command is the interpreter for the Ruby programming language on Linux systems. It allows you to execute Ruby scripts, run interactive Ruby sessions, and perform various Ruby-related operations directly from the terminal. Ruby is known for its elegant syntax and powerful features, making it popular for web development, automation, and scripting tasks.

Installing Ruby on Linux

Before using the ruby command, you need to ensure Ruby is installed on your system. Most Linux distributions include Ruby in their package repositories.

Ubuntu/Debian Installation

sudo apt update
sudo apt install ruby-full

CentOS/RHEL/Fedora Installation

# For CentOS/RHEL
sudo yum install ruby

# For Fedora
sudo dnf install ruby

Verify Installation

ruby --version

Expected Output:

ruby 3.0.4p208 (2022-04-12 revision 3fa771dded) [x86_64-linux-gnu]

Basic ruby Command Syntax

The basic syntax for the ruby command follows this pattern:

ruby [options] [script] [arguments]

Where:

  • [options] – Command-line options to modify Ruby’s behavior
  • [script] – The Ruby script file to execute
  • [arguments] – Arguments to pass to the Ruby script

Running Ruby Scripts

Creating Your First Ruby Script

Let’s create a simple Ruby script to demonstrate basic usage:

nano hello.rb

Add the following content:

#!/usr/bin/env ruby

puts "Hello, World!"
puts "Welcome to Ruby programming!"

# Display current time
puts "Current time: #{Time.now}"

# Simple calculation
x = 10
y = 20
puts "#{x} + #{y} = #{x + y}"

Executing the Script

ruby hello.rb

Output:

Hello, World!
Welcome to Ruby programming!
Current time: 2025-08-25 04:46:30 +0530
10 + 20 = 30

Making Scripts Executable

You can make Ruby scripts executable without explicitly calling the ruby command:

chmod +x hello.rb
./hello.rb

Interactive Ruby Mode

The ruby command can be used to start an interactive Ruby session, which is excellent for testing code snippets and learning Ruby syntax.

Starting Interactive Mode

ruby -i

However, for a better interactive experience, use IRB (Interactive Ruby):

irb

Interactive Session Example:

irb(main):001:0> name = "CodeLucky"
=> "CodeLucky"
irb(main):002:0> puts "Welcome to #{name}!"
Welcome to CodeLucky!
=> nil
irb(main):003:0> [1, 2, 3, 4, 5].map { |n| n * 2 }
=> [2, 4, 6, 8, 10]

Essential ruby Command Options

Version and Help Information

# Display Ruby version
ruby --version
ruby -v

# Show help information
ruby --help
ruby -h

Syntax Checking

Check Ruby script syntax without executing:

ruby -c script.rb

Example with syntax error:

ruby -c broken_script.rb

Output:

broken_script.rb:3: syntax error, unexpected end-of-input

One-liner Execution

Execute Ruby code directly from command line:

ruby -e "puts 'Hello from command line!'"

Output:

Hello from command line!

Multiple One-liners

ruby -e "puts 'Line 1'" -e "puts 'Line 2'" -e "puts 'Result: #{2 + 3}'"

Output:

Line 1
Line 2
Result: 5

Working with Script Arguments

Ruby scripts can accept and process command-line arguments using the ARGV array.

Creating a Script with Arguments

nano greet.rb
#!/usr/bin/env ruby

if ARGV.empty?
  puts "Usage: ruby greet.rb  [age]"
  exit 1
end

name = ARGV[0]
age = ARGV[1]

puts "Hello, #{name}!"

if age
  puts "You are #{age} years old."
  puts age.to_i >= 18 ? "You are an adult." : "You are a minor."
end

puts "Total arguments received: #{ARGV.length}"
puts "All arguments: #{ARGV.inspect}"

Running with Arguments

ruby greet.rb "Alice" "25"

Output:

Hello, Alice!
You are 25 years old.
You are an adult.
Total arguments received: 2
All arguments: ["Alice", "25"]

Advanced ruby Command Features

Loading Libraries and Require Paths

# Add directory to load path
ruby -I/path/to/library script.rb

# Require specific libraries
ruby -rjson -e "puts JSON.generate({name: 'Ruby', version: '3.0'})"

Warning and Debug Options

# Enable warnings
ruby -w script.rb

# Verbose mode
ruby -v script.rb

# Debug mode
ruby -d script.rb

Setting Variables

# Set global variables
ruby -s -e "puts $debug" -- -debug=true

File Processing Examples

Reading and Processing Files

nano file_processor.rb
#!/usr/bin/env ruby

filename = ARGV[0]

unless filename
  puts "Usage: ruby file_processor.rb "
  exit 1
end

unless File.exist?(filename)
  puts "Error: File '#{filename}' not found!"
  exit 1
end

puts "Processing file: #{filename}"
puts "File size: #{File.size(filename)} bytes"
puts "Last modified: #{File.mtime(filename)}"

# Count lines, words, and characters
lines = 0
words = 0
chars = 0

File.foreach(filename) do |line|
  lines += 1
  words += line.split.length
  chars += line.length
end

puts "\nFile Statistics:"
puts "Lines: #{lines}"
puts "Words: #{words}"
puts "Characters: #{chars}"
# Create sample file
echo -e "Hello World\nRuby Programming\nLinux Commands" > sample.txt

# Process the file
ruby file_processor.rb sample.txt

Output:

Processing file: sample.txt
File size: 42 bytes
Last modified: 2025-08-25 04:46:35 +0530

File Statistics:
Lines: 3
Words: 5
Characters: 42

Working with Environment Variables

nano env_example.rb
#!/usr/bin/env ruby

puts "Current user: #{ENV['USER']}"
puts "Home directory: #{ENV['HOME']}"
puts "Shell: #{ENV['SHELL']}"
puts "PATH: #{ENV['PATH']}"

# Set custom environment variable
ENV['RUBY_APP'] = 'CodeLucky Tutorial'
puts "Custom variable: #{ENV['RUBY_APP']}"

# List all environment variables (first 5)
puts "\nFirst 5 environment variables:"
ENV.to_h.first(5).each do |key, value|
  puts "#{key}: #{value}"
end

Error Handling and Debugging

Basic Error Handling

nano error_handling.rb
#!/usr/bin/env ruby

begin
  puts "Enter a number:"
  input = gets.chomp
  number = Integer(input)
  result = 100 / number
  puts "100 / #{number} = #{result}"
  
rescue ZeroDivisionError
  puts "Error: Cannot divide by zero!"
rescue ArgumentError
  puts "Error: Please enter a valid number!"
rescue StandardError => e
  puts "An error occurred: #{e.message}"
ensure
  puts "Operation completed."
end

Running with Error Handling

ruby error_handling.rb

Try entering different inputs like “0”, “abc”, or “5” to see different error handling scenarios.

Performance and Optimization

Benchmarking Ruby Code

nano benchmark_example.rb
#!/usr/bin/env ruby

require 'benchmark'

n = 10000

Benchmark.bm(20) do |x|
  x.report("Array creation:") do
    n.times { Array.new(100) }
  end
  
  x.report("String concatenation:") do
    str = ""
    n.times { str += "x" }
  end
  
  x.report("String interpolation:") do
    n.times { i = rand(100); "Number: #{i}" }
  end
end
ruby benchmark_example.rb

Common Use Cases and Examples

System Administration Script

nano system_info.rb
#!/usr/bin/env ruby

puts "=== System Information ==="
puts "Hostname: #{`hostname`.chomp}"
puts "Uptime: #{`uptime`.chomp}"
puts "Current directory: #{Dir.pwd}"
puts "Ruby version: #{RUBY_VERSION}"
puts "Platform: #{RUBY_PLATFORM}"

puts "\n=== Disk Usage ==="
`df -h`.each_line do |line|
  puts line if line.include?('/dev/')
end

puts "\n=== Running Processes ==="
processes = `ps aux | head -10`
puts processes

Log File Analyzer

nano log_analyzer.rb
#!/usr/bin/env ruby

log_file = ARGV[0] || '/var/log/syslog'

unless File.exist?(log_file)
  puts "Log file not found: #{log_file}"
  exit 1
end

stats = Hash.new(0)
error_count = 0
warning_count = 0

puts "Analyzing log file: #{log_file}"

File.foreach(log_file) do |line|
  # Count different log levels
  case line.downcase
  when /error/
    error_count += 1
  when /warning/
    warning_count += 1
  end
  
  # Extract and count services
  if line =~ /(\w+)\[\d+\]:/
    stats[$1] += 1
  end
end

puts "\n=== Log Analysis Results ==="
puts "Total errors: #{error_count}"
puts "Total warnings: #{warning_count}"
puts "\nTop services by log entries:"
stats.sort_by { |k, v| -v }.first(10).each do |service, count|
  puts "#{service}: #{count}"
end

Best Practices and Tips

1. Script Portability

Always use the shebang line for portable scripts:

#!/usr/bin/env ruby

2. Error Handling

Implement proper error handling for robust scripts:

begin
  # Your code here
rescue => e
  puts "Error: #{e.message}"
  exit 1
end

3. Command-line Argument Validation

if ARGV.empty?
  puts "Usage: #{$0} "
  exit 1
end

4. Performance Considerations

Use appropriate data structures and avoid unnecessary operations in loops.

Troubleshooting Common Issues

Permission Denied

# Make script executable
chmod +x script.rb

Ruby Not Found

# Check if Ruby is installed
which ruby
# Install Ruby if missing
sudo apt install ruby-full

Syntax Errors

# Check syntax before running
ruby -c script.rb

LoadError for Gems

# Install missing gems
gem install gem_name

Conclusion

The ruby command is an essential tool for Ruby developers working on Linux systems. From executing simple scripts to building complex applications, understanding its various options and capabilities will significantly enhance your development workflow. Whether you’re processing files, automating system tasks, or building web applications, the ruby command provides the flexibility and power needed for efficient Ruby development.

Practice with the examples provided in this guide, experiment with different command-line options, and gradually incorporate Ruby scripting into your daily Linux tasks. The combination of Ruby’s elegant syntax and Linux’s powerful command-line environment creates endless possibilities for automation and development.