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# Variables2name = "Ruby"3age = 304is_awesome = true56# String interpolation7puts "Hello, #{name}!"89# Conditional statements10if age > 2011 puts "You're over 20"12elsif age == 2013 puts "You're exactly 20"14else15 puts "You're under 20"16end1718# Ternary operator19status = is_awesome ? "Awesome" : "Not awesome"
Data Structures
Arrays
ruby snippet
1# Creating arrays2fruits = ["apple", "banana", "orange"]3numbers = [1, 2, 3, 4, 5]4mixed = [1, "two", :three, 4.0]56# Array operations7fruits << "mango" # Add to end8fruits.push("strawberry") # Also adds to end9fruits.unshift("kiwi") # Add to beginning10fruits.pop # Remove from end11fruits.shift # Remove from beginning12fruits[2] # Access by index13fruits[-1] # Access last element14fruits[1..3] # Slice (range)
Ruby arrays are dynamic and can hold different types of objects.
Hashes
ruby snippet
1# Creating hashes2person = { "name" => "John", "age" => 30 }3user = { name: "Jane", age: 25 } # Symbol syntax45# Hash operations6person["occupation"] = "Developer" # Add key-value pair7user[:email] = "jane@example.com" # Add with symbol key8person["age"] # Access value9user.keys # Get all keys10user.values # Get all values11user.each { |key, value| puts "#{key}: #{value}" } # Iteration
Control Flow
Loops
ruby snippet
1# While loop2i = 03while i < 54 puts i5 i += 16end78# For loop with range9for i in 0..410 puts i11end1213# Each iterator14[1, 2, 3].each do |num|15 puts num16end1718# Times iterator195.times { |i| puts i }2021# Until loop22j = 023until j >= 524 puts j25 j += 126end
Iterators and Blocks
ruby snippet
1# Single-line block2[1, 2, 3].map { |n| n * 2 } # Returns [2, 4, 6]34# Multi-line block5[1, 2, 3].each do |number|6 squared = number * number7 puts "#{number} squared is #{squared}"8end910# Common iterators11[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 method2def greet(name)3 "Hello, #{name}!"4end56# Method with default parameter7def greet_with_default(name = "World")8 "Hello, #{name}!"9end1011# Method with keyword arguments12def introduce(name:, age:, occupation: "Developer")13 "Meet #{name}, a #{age}-year-old #{occupation}."14end1516# Calling methods17greet("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# Lambda2square = ->(x) { x * x }3square.call(5) # Returns 2545# Proc6greeter = Proc.new { |name| puts "Hello, #{name}!" }7greeter.call("Ruby") # Prints "Hello, Ruby!"89# Passing to methods10def math_operation(numbers, operation)11 numbers.map(&operation)12end1314math_operation([1, 2, 3], square) # Returns [1, 4, 9]
Object-Oriented Ruby
Classes and Objects
ruby snippet
1class Person2 attr_accessor :name, :age34 def initialize(name, age)5 @name = name6 @age = age7 end89 def introduce10 "Hi, I'm #{@name} and I'm #{@age} years old."11 end1213 def birthday14 @age += 115 "Happy birthday! Now I'm #{@age}."16 end17end1819# Creating and using objects20john = Person.new("John", 30)21puts john.introduce22puts john.birthday23john.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 Animal2 def speak3 "Some generic animal sound"4 end5end67class Dog < Animal8 def speak9 "Woof!"10 end11end1213class Cat < Animal14 def speak15 "Meow!"16 end17end1819fido = Dog.new20whiskers = Cat.new21puts fido.speak # "Woof!"22puts whiskers.speak # "Meow!"
Modules and Mixins
ruby snippet
1module Flyable2 def fly3 "I'm flying!"4 end5end67module Swimmable8 def swim9 "I'm swimming!"10 end11end1213class Bird14 include Flyable15end1617class Duck18 include Flyable19 include Swimmable20end2122sparrow = Bird.new23mallard = Duck.new24puts 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 file2File.open("data.txt", "r") do |file|3 file.each_line do |line|4 puts line5 end6end78# Writing to a file9File.open("output.txt", "w") do |file|10 file.puts "Hello, Ruby!"11 file.puts "This is a new line."12end1314# Reading entire file content15content = File.read("data.txt")1617# Checking if file exists18File.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
1begin2 # Code that might raise an exception3 result = 10 / 04rescue ZeroDivisionError => e5 puts "Error: #{e.message}"6rescue => e7 puts "Some other error occurred: #{e.message}"8else9 puts "No errors occurred"10ensure11 puts "This code always runs"12end1314# Custom exceptions15class CustomError < StandardError16 def initialize(msg = "A custom error occurred")17 super18 end19end2021begin22 raise CustomError.new("Something went wrong")23rescue CustomError => e24 puts e.message25end
Useful Ruby Tools
RubyGems
ruby snippet
1# Installing a gem2gem install nokogiri34# Listing installed gems5gem list67# Updating a gem8gem update rails910# Uninstalling a gem11gem uninstall nokogiri
Bundler
ruby snippet
1# Installing bundler2gem install bundler34# Installing gems from Gemfile5bundle install67# Updating gems8bundle update910# Running a command in the context of the bundle11bundle exec rspec
Bundler helps manage gem dependencies for your Ruby applications.
Regular Expressions
ruby snippet
1# Basic pattern matching2"hello" =~ /ello/ # Returns 1 (index of match)34# Pattern with modifiers5"Hello World" =~ /hello/i # Case-insensitive match67# String methods with regex8"hello".gsub(/[aeiou]/, '*') # "h*ll*"9"hello world".scan(/\w+/) # ["hello", "world"]1011# Matching groups12match_data = "John Smith".match(/(\w+) (\w+)/)13first_name = match_data[1] # "John"14last_name = match_data[2] # "Smith"
Happy coding with Ruby!