AI Generate Ruby docs instantly

Ruby Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Your first steps with Ruby basics

Hello World

puts "Hello, World!"

Comments

# Single line comment
=begin
Multi-line
comment
=end

User Input

print "Name: "
name = gets.chomp

Type Conversion

"42".to_i   # string to int
42.to_s     # int to string
"3.14".to_f # to float

Check Type

variable.class      # String, Integer
variable.is_a?(String)  # true/false

Variables & Data Types

7 snippets

Declaring and using different data types

String

name = "John"

Integer

age = 25

Float

price = 19.99

Array

fruits = ["apple", "banana", "cherry"]

Hash

person = { name: "John", age: 30 }

Symbol

:status

Range

(1..5)  # 1 to 5 inclusive
(1...5) # 1 to 4

Operators

6 snippets

Symbols for calculations and comparisons

Arithmetic

5 + 3   # 8 (addition)
5 - 3   # 2 (subtraction)
5 * 3   # 15 (multiplication)
5 / 3   # 1 (integer division)
5.0 / 3 # 1.666... (float division)
5 % 3   # 2 (modulus)
5 ** 3  # 125 (exponent)

Comparison

5 == 5  # true (equal)
5 != 3  # true (not equal)
5 > 3   # true (greater)
5 <=> 3 # 1 (spaceship: -1, 0, 1)
5.eql?(5)   # true (same type)

Logical

true && false   # false (AND)
true || false   # true (OR)
!true           # false (NOT)
true and false  # false (lower precedence)
true or false   # true (lower precedence)

Assignment

x = 5     # Assign
x += 3    # x = 8 (add)
x -= 2    # x = 6 (subtract)
x *= 2    # x = 12 (multiply)
x ||= 10  # x = 12 (assign if nil/false)

Range

(1..5)   # 1, 2, 3, 4, 5 (inclusive)
(1...5)  # 1, 2, 3, 4 (exclusive)
('a'..'e').to_a  # ["a", "b", "c", "d", "e"]

Safe Navigation

user&.name       # nil if user is nil
user&.profile&.email  # safe chain

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Loops

9 snippets

Repeating code blocks efficiently

Each

(1..5).each do |i|
  puts i
end

Each One-liner

[1, 2, 3].each { |n| puts n }

Times

5.times { |i| puts i }  # 0, 1, 2, 3, 4

Upto/Downto

1.upto(5) { |i| puts i }
5.downto(1) { |i| puts i }

While

while count < 10
  count += 1
end

Until

until count >= 10
  count += 1
end

Loop

loop do
  break if done
end

Each with Index

arr.each_with_index do |item, i|
  puts "#{i}: #{item}"
end

Break/Next

(1..10).each do |i|
  next if i == 5   # skip
  break if i == 8  # exit
  puts i
end

Conditionals

5 snippets

Making decisions in your code

If/Else

if x > 0
  puts "positive"
elsif x < 0
  puts "negative"
else
  puts "zero"
end

Unless

puts "active" unless inactive

Ternary

result = condition ? "yes" : "no"

Case

case day
when "Mon"
  puts "Monday"
when "Tue", "Wed"
  puts "Midweek"
else
  puts "Other"
end

One-line If

puts "big" if x > 100

Methods

5 snippets

Method

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

Default Arg

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

Splat Args

def sum(*nums)
  nums.reduce(0, :+)
end

Keyword Args

def greet(name:, age: 0)
  "#{name} is #{age}"
end

Block

def with_timing
  start = Time.now
  yield
  Time.now - start
end

Array Methods

6 snippets

Map

[1, 2, 3].map { |n| n * 2 }

Select

[1, 2, 3, 4].select { |n| n.even? }

Reject

[1, 2, 3, 4].reject { |n| n.even? }

Reduce

[1, 2, 3].reduce(0) { |sum, n| sum + n }

Find

users.find { |u| u.id == 1 }

Sort

[3, 1, 2].sort
users.sort_by { |u| u.age }

Classes & OOP

4 snippets

Class

class Dog
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def bark
    "#{@name} says woof!"
  end
end

Inheritance

class Puppy < Dog
  def play
    "#{@name} is playing!"
  end
end

Module

module Greetable
  def greet
    "Hello!"
  end
end

Include

class Person
  include Greetable
end

String Operations

6 snippets

Interpolation

"Hello, #{name}!"

Concatenate

"Hello" + " " + "World"

Split

"a,b,c".split(",")

Join

["a", "b", "c"].join(",")

Strip

"  hello  ".strip

Replace

"hello".gsub("l", "x")

Error Handling

3 snippets

Begin/Rescue

begin
  risky_operation
rescue StandardError => e
  puts e.message
end

Ensure

begin
  # code
rescue
  # handle
ensure
  cleanup
end

Raise

raise ArgumentError, "Invalid input"

More Cheat Sheets

FAQ

Frequently asked questions

What is a Ruby cheat sheet?

A Ruby cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Ruby. It helps developers quickly look up syntax without searching through documentation.

How do I learn Ruby quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Ruby concepts?

Key Ruby concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Ruby code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Ruby code using AI.

Code Conversion Tools

Convert Ruby to Other Languages

Easily translate your Ruby code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate Ruby Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week