Skip to content

Ruby Cheat Sheet

Ruby is a dynamic, object-oriented programming language focused on simplicity and expressiveness. This Ruby cheatsheet provides an example-driven reference for core Ruby syntax, objects, collections, blocks, classes, modules, and common standard library features.


Basic Program

puts "Hello, Ruby"

Variables

a = 10
b = "text"
c = true
@instance_var = 1
@@class_var = 2
$global_var = 3

Data Types

Integer
Float
String
Symbol
Array
Hash
Boolean
NilClass
10.class
"text".class

Strings

s = "Ruby"

s.length
s.upcase
s.include?("Ru")
name = "World"
"Hello #{name}"

Symbols

:key
:name
:key.object_id

Operators

a + b
a - b
a * b
a / b
a % b
a == b
a != b
a > b
a < b
a && b
a || b
!a

Control Flow

if / elsif / else

if a > 10
  "large"
elsif a > 5
  "medium"
else
  "small"
end

case

case a
when 1
  "one"
when 2
  "two"
else
  "other"
end

Loops

for i in 1..5
  puts i
end
while a > 0
  a -= 1
end
5.times do |i|
  puts i
end

Methods

def add(a, b)
  a + b
end
add(2, 3)

Default Parameters

def multiply(a, b = 2)
  a * b
end

Splat Operator

def total(*nums)
  nums.sum
end

Arrays

arr = [1, 2, 3]
arr << 4
arr[0]

Array Methods

arr.map { |n| n * 2 }
arr.select { |n| n > 1 }
arr.find { |n| n == 2 }

Hashes

h = { a: 1, b: 2 }
h[:a]
h[:b] = 3

Iteration

arr.each do |item|
  puts item
end
h.each do |k, v|
  puts "#{k}: #{v}"
end

Blocks

[1, 2, 3].each { |n| puts n }
[1, 2, 3].map do |n|
  n * 2
end

Procs & Lambdas

proc_obj = Proc.new { |x| x * 2 }
lambda_obj = ->(x) { x * 2 }
proc_obj.call(5)
lambda_obj.call(5)

Classes

class Counter
  def initialize
    @value = 0
  end

  def increment
    @value += 1
  end

  def value
    @value
  end
end

Inheritance

class Animal
  def speak; end
end

class Dog < Animal
end

Modules

module MathUtil
  def add(a, b)
    a + b
  end
end
class Box
  include MathUtil
end

Mixins

module Loggable
  def log(msg)
    puts msg
  end
end
class App
  include Loggable
end

Access Control

private
protected
public

Exceptions

begin
  raise "error"
rescue => e
  puts e.message
ensure
end

File I/O

File.write("file.txt", "text")
content = File.read("file.txt")

Symbols vs Strings

"key".to_sym
:key.to_s

Enumerable

arr.reduce(0) { |sum, n| sum + n }
arr.any? { |n| n > 2 }
arr.all? { |n| n > 0 }

Time & Date

Time.now

Require

require "json"