Ruby Cheatsheet

Basic Syntax Variables Data Types Strings Numbers Symbols Arrays Hashes Ranges Control Flow Methods Blocks Procs Lambdas Classes Objects Inheritance Modules Mixins Enumerables Iterators File I/O Exception Handling Regex Useful Built-ins Gems Require/Load

Basic Syntax

Syntax
# Single line comment
puts "Hello, World!"
# IRB: Interactive Ruby
# $ irb

Variables

Variable
x = 5
name = "Alice"
flag = true

Data Types

Data Type
# Integer, Float, String, Symbol, Array, Hash, NilClass, TrueClass, FalseClass
5.class # Integer
3.14.class # Float
"hi".class # String
:foo.class # Symbol
[1,2].class # Array
{a:1}.class # Hash
nil.class # NilClass
true.class # TrueClass
false.class # FalseClass

Strings

String
s = "Hello"
s2 = 'World'
len = s.length
up = s.upcase
name = "Alice"
msg = "Hi, #{name}!"

Numbers

Number
a = 5
b = 2.5
sum = a + b
prod = a * b
quot = a / b
mod = a % 2
exp = a ** 2
"42".to_i # 42
3.14.to_s # "3.14"

Symbols

Symbol
sym = :my_symbol
sym2 = "name".to_sym
:foo == :foo # true
:foo.object_id == :foo.object_id # true
"foo".object_id == "foo".object_id # false

Arrays

Array
arr = [1, 2, 3]
arr << 4
arr[0] # 1
arr[1..2] # [2, 3]
arr.each { |n| puts n }
arr.map { |n| n * 2 }
arr.include?(2) # true
arr.reverse # [4,3,2,1]

Hashes

Hash
h = {a: 1, b: 2}
h[:a] # 1
h[:c] = 3
h.each { |k, v| puts "#{k}: #{v}" }

Ranges

Range
r = (1..5).to_a # [1,2,3,4,5]
('a'..'c').to_a # ["a","b","c"]
(1...5).to_a # [1,2,3,4]

Control Flow

Control
if x > 0
  puts "Positive"
elsif x == 0
  puts "Zero"
else
  puts "Negative"
end

for i in 1..3
  puts i
end

3.times { puts "Hi" }

Methods

Method
def add(a, b)
  a + b
end

def greet(name = "World")
  puts "Hello, #{name}!"
end

Blocks

Block
def repeat(n)
  n.times { yield }
end
repeat(3) { puts "Hello" }
[1,2,3].each { |x| puts x }

Procs

Proc
p = Proc.new { |x| puts x }
p.call(5)
[1,2,3].each(&p)

Lambdas

Lambda
l = ->(x) { x * 2 }
puts l.call(3) # 6

Classes

Class
class Person
  attr_accessor :name
  def initialize(name)
    @name = name
  end
  def greet
    puts "Hi, I'm #{@name}"
  end
end
p = Person.new("Bob")
p.greet

Objects

Object
p = Person.new("Alice")
p.name = "Eve"
puts p.name

Inheritance

Inheritance
class Animal
  def speak
    puts "..."
  end
end
class Dog < Animal
  def speak
    puts "Woof"
  end
end
Dog.new.speak

Modules

Module
module MathUtils
  def self.add(a, b)
    a + b
  end
end
puts MathUtils.add(5, 3)

Mixins

Mixin
module StringExtensions
  def reverse_words
    self.split.reverse.join(' ')
  end
end

class String
  include StringExtensions
end

puts "Hello World".reverse_words

Enumerables

Enumerable
arr = [1, 2, 3, 4, 5]
sum = arr.reduce(0) { |acc, n| acc + n }
puts sum

arr.each_with_index { |item, index| puts "#{index}: #{item}" }

arr.select { |n| n.even? } # [2, 4]
arr.reject { |n| n.even? } # [1, 3, 5]

Iterators

Iterator
5.times { |i| puts i }
[1,2,3].each_with_index { |v, i| puts "#{i}: #{v}" }
(1..3).step(2) { |n| puts n }
loop do
  break
end

File I/O

File I/O
File.open("test.txt", "w") do |f|
  f.puts "Hello, World!"
end

File.read("test.txt")

File.delete("test.txt")

Exception Handling

Exception
begin
  # Code that might raise an exception
  raise "Error!"
rescue StandardError => e
  puts "Caught an exception: #{e.message}"
ensure
  puts "This will always execute"
end

Regex

Regex
text = "Hello, Ruby!"
match = text.match(/Ruby/)
puts match[0] # Ruby

text.gsub(/Ruby/, "Rails") # Hello, Rails!

text.scan(/[a-z]+/) # ["Hello", "Ruby"]

Useful Built-ins

Built-in
puts "Hello".length # 5
puts "Hello".upcase # HELLO
puts "Hello".downcase # hello
puts "Hello".reverse # olleH

puts [1, 2, 3].include?(2) # true
puts [1, 2, 3].max # 3
puts [1, 2, 3].min # 1

puts 10.even? # false
puts 10.odd? # true

puts 10.to_s # "10"
puts 10.to_f # 10.0
puts 10.to_i # 10

Gems

Gem
# Install a gem:
# $ gem install rails

require 'date'
puts Date.today

# Gemfile (for Bundler):
# gem 'rails'
# $ bundle install

Require/Load

Require/Load
require './my_script'
load './my_script.rb'

require 'json'
puts JSON.generate([1,2,3])