Ruby Commands & Snippets

Essential Ruby Commands & Snippets

A comprehensive guide to Ruby syntax, commands, and code snippets for my everyday study and reference.

Ruby Basics

Running Ruby Scripts

test.rb
1ruby script.rb

Interactive Ruby Shell (IRB)

ruby snippet
1irb
Use puts for debugging in IRB:
ruby snippet
1irb(main):001:0> puts "Hello, Ruby!"
2Hello, Ruby!
3=> nil

Basic Syntax

ruby snippet
1# Variables
2name = "Ruby"
3age = 30
4is_awesome = true
5
6# String interpolation
7puts "Hello, #{name}!"
8
9# Conditional statements
10if age > 20
11 puts "You're over 20"
12elsif age == 20
13 puts "You're exactly 20"
14else
15 puts "You're under 20"
16end
17
18# Ternary operator
19status = is_awesome ? "Awesome" : "Not awesome"

Data Structures

Arrays

ruby snippet
1# Creating arrays
2fruits = ["apple", "banana", "orange"]
3numbers = [1, 2, 3, 4, 5]
4mixed = [1, "two", :three, 4.0]
5
6# Array operations
7fruits << "mango" # Add to end
8fruits.push("strawberry") # Also adds to end
9fruits.unshift("kiwi") # Add to beginning
10fruits.pop # Remove from end
11fruits.shift # Remove from beginning
12fruits[2] # Access by index
13fruits[-1] # Access last element
14fruits[1..3] # Slice (range)
Ruby arrays are dynamic and can hold different types of objects.

Hashes

ruby snippet
1# Creating hashes
2person = { "name" => "John", "age" => 30 }
3user = { name: "Jane", age: 25 } # Symbol syntax
4
5# Hash operations
6person["occupation"] = "Developer" # Add key-value pair
7user[:email] = "jane@example.com" # Add with symbol key
8person["age"] # Access value
9user.keys # Get all keys
10user.values # Get all values
11user.each { |key, value| puts "#{key}: #{value}" } # Iteration

Control Flow

Loops

ruby snippet
1# While loop
2i = 0
3while i < 5
4 puts i
5 i += 1
6end
7
8# For loop with range
9for i in 0..4
10 puts i
11end
12
13# Each iterator
14[1, 2, 3].each do |num|
15 puts num
16end
17
18# Times iterator
195.times { |i| puts i }
20
21# Until loop
22j = 0
23until j >= 5
24 puts j
25 j += 1
26end

Iterators and Blocks

ruby snippet
1# Single-line block
2[1, 2, 3].map { |n| n * 2 } # Returns [2, 4, 6]
3
4# Multi-line block
5[1, 2, 3].each do |number|
6 squared = number * number
7 puts "#{number} squared is #{squared}"
8end
9
10# Common iterators
11[1, 2, 3, 4].select { |n| n.even? } # Returns [2, 4]
12[1, 2, 3, 4].reject { |n| n.even? } # Returns [1, 3]
13[1, 2, 3].reduce(0) { |sum, n| sum + n } # Returns 6
Ruby has many built-in iterators that make working with collections easy and expressive.

Methods and Functions

Defining Methods

ruby snippet
1# Basic method
2def greet(name)
3 "Hello, #{name}!"
4end
5
6# Method with default parameter
7def greet_with_default(name = "World")
8 "Hello, #{name}!"
9end
10
11# Method with keyword arguments
12def introduce(name:, age:, occupation: "Developer")
13 "Meet #{name}, a #{age}-year-old #{occupation}."
14end
15
16# Calling methods
17greet("Ruby") # "Hello, Ruby!"
18greet_with_default() # "Hello, World!"
19introduce(name: "John", age: 30) # "Meet John, a 30-year-old Developer."

Lambda and Proc

ruby snippet
1# Lambda
2square = ->(x) { x * x }
3square.call(5) # Returns 25
4
5# Proc
6greeter = Proc.new { |name| puts "Hello, #{name}!" }
7greeter.call("Ruby") # Prints "Hello, Ruby!"
8
9# Passing to methods
10def math_operation(numbers, operation)
11 numbers.map(&operation)
12end
13
14math_operation([1, 2, 3], square) # Returns [1, 4, 9]

Object-Oriented Ruby

Classes and Objects

ruby snippet
1class Person
2 attr_accessor :name, :age
3
4 def initialize(name, age)
5 @name = name
6 @age = age
7 end
8
9 def introduce
10 "Hi, I'm #{@name} and I'm #{@age} years old."
11 end
12
13 def birthday
14 @age += 1
15 "Happy birthday! Now I'm #{@age}."
16 end
17end
18
19# Creating and using objects
20john = Person.new("John", 30)
21puts john.introduce
22puts john.birthday
23john.name = "Johnny"
attr_accessor creates both getter and setter methods. Use attr_reader for read-only and attr_writer for write-only attributes.

Inheritance

ruby snippet
1class Animal
2 def speak
3 "Some generic animal sound"
4 end
5end
6
7class Dog < Animal
8 def speak
9 "Woof!"
10 end
11end
12
13class Cat < Animal
14 def speak
15 "Meow!"
16 end
17end
18
19fido = Dog.new
20whiskers = Cat.new
21puts fido.speak # "Woof!"
22puts whiskers.speak # "Meow!"

Modules and Mixins

ruby snippet
1module Flyable
2 def fly
3 "I'm flying!"
4 end
5end
6
7module Swimmable
8 def swim
9 "I'm swimming!"
10 end
11end
12
13class Bird
14 include Flyable
15end
16
17class Duck
18 include Flyable
19 include Swimmable
20end
21
22sparrow = Bird.new
23mallard = Duck.new
24puts sparrow.fly # "I'm flying!"
25puts mallard.fly # "I'm flying!"
26puts mallard.swim # "I'm swimming!"
Modules are great for sharing functionality across unrelated classes. They solve the multiple inheritance problem.

File Operations

ruby snippet
1# Reading a file
2File.open("data.txt", "r") do |file|
3 file.each_line do |line|
4 puts line
5 end
6end
7
8# Writing to a file
9File.open("output.txt", "w") do |file|
10 file.puts "Hello, Ruby!"
11 file.puts "This is a new line."
12end
13
14# Reading entire file content
15content = File.read("data.txt")
16
17# Checking if file exists
18File.exist?("data.txt")
Always close files when you're done with them. Using blocks with File.open automatically closes the file when the block ends.

Exception Handling

ruby snippet
1begin
2 # Code that might raise an exception
3 result = 10 / 0
4rescue ZeroDivisionError => e
5 puts "Error: #{e.message}"
6rescue => e
7 puts "Some other error occurred: #{e.message}"
8else
9 puts "No errors occurred"
10ensure
11 puts "This code always runs"
12end
13
14# Custom exceptions
15class CustomError < StandardError
16 def initialize(msg = "A custom error occurred")
17 super
18 end
19end
20
21begin
22 raise CustomError.new("Something went wrong")
23rescue CustomError => e
24 puts e.message
25end

Useful Ruby Tools

RubyGems

ruby snippet
1# Installing a gem
2gem install nokogiri
3
4# Listing installed gems
5gem list
6
7# Updating a gem
8gem update rails
9
10# Uninstalling a gem
11gem uninstall nokogiri

Bundler

ruby snippet
1# Installing bundler
2gem install bundler
3
4# Installing gems from Gemfile
5bundle install
6
7# Updating gems
8bundle update
9
10# Running a command in the context of the bundle
11bundle exec rspec
Bundler helps manage gem dependencies for your Ruby applications.

Regular Expressions

ruby snippet
1# Basic pattern matching
2"hello" =~ /ello/ # Returns 1 (index of match)
3
4# Pattern with modifiers
5"Hello World" =~ /hello/i # Case-insensitive match
6
7# String methods with regex
8"hello".gsub(/[aeiou]/, '*') # "h*ll*"
9"hello world".scan(/\w+/) # ["hello", "world"]
10
11# Matching groups
12match_data = "John Smith".match(/(\w+) (\w+)/)
13first_name = match_data[1] # "John"
14last_name = match_data[2] # "Smith"
Happy coding with Ruby!