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" # ConstantControl Flow
Conditionals
# Conditional
if age > 18
puts "Adult"
elsif age > 12
puts "Teen"
else
puts "Child"
end
# Inline If
puts "Hi" if conditionLoops
3.times { puts "Hello" }
[1, 2, 3].each do |i|
puts i
endMethods & 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
endEnumerable 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 newlinegets: Get user input.nil?: Check if nil.empty?: Check if collection is empty
Common Commands (CLI)
ruby main.rb: Run scriptirb: Interactive Ruby consolegem install <name>: Install gem packagebundle install: Install project dependenciesrake <task>: Execute task script