Ruby OS Interaction provides extensive capabilities for system-level operations through built-in classes and methods.
Ruby treats the operating system as a first-class citizen, offering multiple ways to execute commands, manipulate files, and interact with system resources.
System Command Execution: Ruby offers several methods to execute OS commands:
# Using backticks - captures output
output = `ls -la`
puts output
# Using system() - returns true/false
success = system("mkdir test_dir")
puts "Command succeeded: #{success}"
# Using %x{} - alternative to backticks
files = %x{find . -name "*.rb"}
puts files
# Using Open3 for advanced control
require 'open3'
stdout, stderr, status = Open3.capture3("ls /nonexistent")
puts "Exit code: #{status.exitstatus}"
File and Directory Operations:
# Directory operations
Dir.mkdir("new_folder") unless Dir.exist?("new_folder")
Dir.chdir("new_folder")
puts "Current directory: #{Dir.pwd}"
# List directory contents
Dir.glob("*.txt").each { |file| puts file }
# File operations
File.open("sample.txt", "w") { |f| f.write("Hello OS!") }
content = File.read("sample.txt") if File.exist?("sample.txt")
# File permissions and info
File.chmod(0755, "sample.txt")
puts "File size: #{File.size("sample.txt")} bytes"
puts "Modified: #{File.mtime("sample.txt")}"
Environment Variables and Process Control:
# Environment variables
puts "PATH: #{ENV['PATH']}"
ENV['MY_VAR'] = "custom_value"
# Process information
puts "Process ID: #{Process.pid}"
puts "Parent PID: #{Process.ppid}"
# Fork process (Unix-like systems)
if RUBY_PLATFORM !~ /mswin|mingw/
pid = fork do
puts "Child process: #{Process.pid}"
end
Process.wait(pid) if pid
end
Platform Detection and System Info:
require 'rbconfig'
puts "OS: #{RbConfig::CONFIG['host_os']}"
puts "Architecture: #{RbConfig::CONFIG['host_cpu']}"
puts "Ruby version: #{RUBY_VERSION}"
# Platform-specific operations
case RbConfig::CONFIG['host_os']
when /mswin|mingw|cygwin/
system("dir") # Windows
when /darwin|mac os/
system("ls -la") # macOS
when /linux/
system("ps aux") # Linux
end
Temporary Files and Cleanup:
require 'tempfile'
temp = Tempfile.new('ruby_temp')
temp.write("Temporary data")
temp.close
puts "Temp file: #{temp.path}"
temp.unlink # Clean up
Ruby's OS interaction capabilities make it excellent for system administration, automation scripts, and DevOps tasks, providing cross-platform compatibility with platform-specific optimizations when needed.