Skip to main content

Ruby OS Interaction

Ruby isn't just for shuffling numbers and text around — it can also reach out and poke the actual operating system: run commands, create files, check what machine it's running on, all that. Here's what that looks like, broken down simply.

Running commands like you would in a terminal

There are a few different ways to tell Ruby "hey, run this shell command for me":

output = `ls -la`        # backticks: run it, hand me back whatever it printed
puts output

Think of backticks like texting a friend "what's in your fridge?" and they text back the whole list.

success = system("mkdir test_dir")   # just tells you true/false: did it work?

This one doesn't care what the command printed — just whether it succeeded or not.

files = %x{find . -name "*.rb"}      # same idea as backticks, just different-looking syntax
require 'open3'
stdout, stderr, status = Open3.capture3("ls /nonexistent")

Open3 is the "grown-up" option — it separates the normal output, the error messages, and the exit code (a number that tells you if something failed) into three neat little boxes instead of mashing it all together.

Making and messing with files/folders

Dir.mkdir("new_folder") unless Dir.exist?("new_folder")
Dir.chdir("new_folder")
puts Dir.pwd   # "where am I right now?"

This says: "make a folder, but only if it doesn't already exist, then step inside it."

Dir.glob("*.txt").each { |file| puts file }

Translation: "find every file ending in .txt and print its name, one by one."

File.open("sample.txt", "w") { |f| f.write("Hello OS!") }
content = File.read("sample.txt") if File.exist?("sample.txt")

Open a file in "write" mode, put text in it, close it automatically. Then read it back — but only if it actually exists (so you don't crash trying to read something that isn't there).

File.chmod(0755, "sample.txt")   # sets who's allowed to read/write/run this file
puts File.size("sample.txt")     # how big is it, in bytes
puts File.mtime("sample.txt")    # when was it last changed

Environment variables and process stuff

An environment variable is just a little labeled setting your whole computer can see — like a sticky note the OS keeps handy.

puts ENV['PATH']          # read one
ENV['MY_VAR'] = "custom_value"   # create/change one

Every running program has an ID number (like a name tag) so the OS can keep track of it:

puts Process.pid    # "what's MY ID number?"
puts Process.ppid   # "what's the ID of whoever started me?"

Forking is a neat (and slightly weird) trick where a program basically clones itself into a second, independent copy:

if RUBY_PLATFORM !~ /mswin|mingw/   # skip this on Windows, it doesn't support forking
  pid = fork do
    puts "Child process: #{Process.pid}"
  end
  Process.wait(pid) if pid   # wait for the clone to finish before moving on
end

Imagine hitting "duplicate" on yourself, having your clone go do a task, and you just standing there waiting for them to finish.

Figuring out what computer you're on

require 'rbconfig'
puts RbConfig::CONFIG['host_os']    # e.g. "linux", "darwin" (that's mac), "mingw" (windows)
puts RbConfig::CONFIG['host_cpu']
puts RUBY_VERSION

You can even make your script behave differently depending on the OS it's running on:

case RbConfig::CONFIG['host_os']
when /mswin|mingw|cygwin/
  system("dir")        # Windows uses "dir" instead of "ls"
when /darwin|mac os/
  system("ls -la")     # Mac
when /linux/
  system("ps aux")     # Linux
end

It's like a script that speaks three different dialects and automatically picks the right one depending on where it wakes up.

Temporary, throwaway files

Sometimes you just need a scratch file that disappears when you're done — no cleanup headaches:

require 'tempfile'

temp = Tempfile.new('ruby_temp')
temp.write("Temporary data")
temp.close
puts temp.path   # where did Ruby put it?
temp.unlink      # delete it, all cleaned up

Like writing a note on a napkin, using it, then tossing the napkin — instead of a permanent notebook.

Why any of this matters

All of this is what makes Ruby genuinely good at system administration, automation, and DevOps work — scripts that create folders, run shell commands, check what machine they're on, and clean up after themselves, all without you touching the terminal by hand.

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...