Skip to content

Ruby Programming Language Cheat Sheet

Ruby is a dynamic, open-source, object-oriented programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.

Basics

Common Objects

  • Strings: "hello", 'world'
  • Symbols: :id, :name (immutable and unique)
  • Numbers: 10, 3.14
  • Arrays: [1, 2, 3]
  • Hashes: { key: "value" }

Variables

# Variable types
name = "Ruby"   # Local
@name = "Ruby"  # Instance
@@name = "Ruby" # Class
$name = "Ruby"  # Global
NAME = "Ruby"   # Constant

Control Flow

Conditionals

# Conditional
if age > 18
  puts "Adult"
elsif age > 12
  puts "Teen"
else
  puts "Child"
end

# Inline If
puts "Hi" if condition

Loops

3.times { puts "Hello" }

[1, 2, 3].each do |i|
  puts i
end

Methods & Classes

# Method definition
def greet(name = "Guest")
  "Hello, #{name}!"
end

# Class definition
class Animal
  attr_accessor :name # Automatically generate getter/setter
  
  def initialize(name)
    @name = name
  end
  
  def speak
    "..."
  end
end

Enumerable Operations

Method Description Example
each Iterate through each element `[1,2].each {
map Transform each element and return new array `[1,2].map {
select Filter elements matching condition `[1,2,3].select {
reject Filter out elements matching condition `[1,2,3].reject {
reduce Reduce to a single value [1,2,3].reduce(0, :+)

Common Built-in Methods

  • p object : Print object (with type info)
  • puts object : Output object with newline
  • gets : Get user input
  • .nil? : Check if nil
  • .empty? : Check if collection is empty

Common Commands (CLI)

  • ruby main.rb : Run script
  • irb : Interactive Ruby console
  • gem install <name> : Install gem package
  • bundle install : Install project dependencies
  • rake <task> : Execute task script