Ruby Cheat Sheet
Ruby reference with blocks, hashes, OOP, enumerables, and idiomatic patterns. Copy-ready code snippets for Ruby developers.
Variables
| Syntax | Description | Example |
|---|---|---|
| Local variable assignment | name = 'Alice' | |
| Instance variable | @name = 'Alice' | |
| Class variable | @@count = 0 | |
| Global variable | $debug = true | |
| Constant (uppercase convention) | MAX_SIZE = 100 | |
| Output to console | puts 'Hello'; p [1,2,3] | |
| Get the class/type of an object | 42.class → Integer | |
| Check if value is nil | nil.nil? → true | |
| Make object immutable | name = 'Alice'.freeze |
Strings
| Syntax | Description | Example |
|---|---|---|
| String length | 'hello'.length → 5 | |
| Change case | 'hello'.upcase → 'HELLO' | |
| Remove leading/trailing whitespace | ' hi '.strip → 'hi' | |
| Split string into array | 'a,b,c'.split(',') → ['a','b','c'] | |
| Join array into string | ['a','b'].join(', ') → 'a, b' | |
| Global substitution | 'hello'.gsub('l','r') → 'herro' | |
| Replace first occurrence | 'hello'.sub('l','r') → 'herlo' | |
| Check if string contains substring | 'hello'.include?('ell') → true | |
| Check start/end of string | 'hello'.start_with?('he') → true | |
| String interpolation (double quotes) | "Hi #{name}, age #{age}" | |
| Convert to array of chars/bytes | 'hi'.chars → ['h','i'] | |
| Type conversion | '42'.to_i → 42 | |
| Reverse a string | 'hello'.reverse → 'olleh' |
Arrays
| Syntax | Description | Example |
|---|---|---|
| Create an array | fruits = ['apple', 'banana'] | |
| Add to end of array | arr << 4; arr.push(5) | |
| Remove from end / beginning | arr.pop → last element | |
| Add to beginning | arr.unshift('first') | |
| Sort array | [3,1,2].sort → [1,2,3] | |
| Reverse array | [1,2,3].reverse → [3,2,1] | |
| Flatten nested arrays | [[1,2],[3]].flatten → [1,2,3] | |
| Remove nil values | [1,nil,3].compact → [1,3] | |
| Remove duplicates | [1,2,2,3].uniq → [1,2,3] | |
| Transform each element | [1,2,3].map { |x| x*2 } → [2,4,6] | |
| Filter elements | [1,2,3].select { |x| x>1 } → [2,3] | |
| Remove matching elements | [1,2,3].reject { |x| x>1 } → [1] | |
| Reduce to single value | [1,2,3].reduce(0) { |sum, x| sum+x } → 6 | |
| Iterate over elements | arr.each { |item| puts item } | |
| Iterate with index | arr.each_with_index { |x,i| puts "#{i}: #{x}" } | |
| Get first/last n elements | [1,2,3].first(2) → [1,2] | |
| Combine arrays element-wise | [1,2].zip(['a','b']) → [[1,'a'],[2,'b']] |
Hashes
| Syntax | Description | Example |
|---|---|---|
| Create a hash (symbol keys) | user = { name: 'Alice', age: 30 } | |
| Access value by key | user[:name] → 'Alice' | |
| Get with default/error | h.fetch(:name, 'Unknown') | |
| Get all keys or values | user.keys → [:name, :age] | |
| Iterate over pairs | h.each { |k,v| puts "#{k}: #{v}" } | |
| Merge two hashes | h.merge({ email: 'a@b.com' }) | |
| Filter hash entries | h.select { |k,v| v > 0 } | |
| Transform all values | h.transform_values { |v| v.upcase } | |
| Check if key/value exists | user.key?(:name) → true | |
| Remove a key-value pair | h.delete(:age) |
Control Flow
| Syntax | Description | Example |
|---|---|---|
| Conditional branching | if x > 0 then ... elsif ... else ... end | |
| Negative conditional | unless logged_in? then redirect end | |
| Inline conditional (modifier) | puts 'hi' if greeting | |
| Pattern matching | case x when 1..5 then 'low' when 6..10 then 'high' end | |
| Loop until condition | while i < 10 do i += 1 end | |
| Loop n times | 5.times { |i| puts i } | |
| Range iteration | (1..10).each { |i| puts i } | |
| Exception handling | begin ... rescue StandardError => e ... end | |
| Raise an exception | raise ArgumentError, 'Invalid input' |
Methods
| Syntax | Description | Example |
|---|---|---|
| Define a method | def greet(name) "Hi #{name}" end | |
| Default parameter value | def add(a, b=0) a+b end | |
| Splat operator (variable args) | def sum(*nums) nums.sum end | |
| Double splat (keyword args) | def configure(**opts) ... end | |
| Lambda | double = -> (x) { x * 2 }; double.call(5) | |
| Proc object | square = Proc.new { |x| x**2 } | |
| Execute block passed to method | def wrap; puts 'before'; yield; puts 'after'; end | |
| Capture block as parameter | def apply(&block) block.call(42) end |
OOP
| Syntax | Description | Example |
|---|---|---|
| Define a class | class User; attr_accessor :name; end | |
| Auto-generate getters/setters | attr_accessor :name, :email | |
| Constructor | def initialize(name) @name = name end | |
| Inheritance | class Admin < User; end | |
| Define a module | module Cacheable; def cache; end; end | |
| Mix in a module | class Post; include Cacheable; end | |
| Reference to current object | def self.class_method; end | |
| Check if object has method | obj.respond_to?(:name) → true |
Frequently asked questions
What's the difference between a symbol and a string?
Symbols (:name) are immutable, interned identifiers - each symbol with the same name is the same object in memory. Strings ('name') are mutable and each instance is a separate object. Use symbols for identifiers (hash keys, status labels) and strings for data (user input, output).
When should I use Ruby vs Python?
Ruby excels at web development (Rails), DSLs, and developer happiness. Python excels at data science, ML, and scripting. Ruby is more object-oriented; Python is more procedural. Both are great general-purpose languages - choose based on your ecosystem needs.
What's the difference between Proc and Lambda?
Both are callable objects. Lambda checks argument count and returns to the calling method. Proc doesn't check arguments and 'return' exits the enclosing method. Lambdas behave more like methods; Procs behave more like blocks.
What is monkey patching?
Ruby allows reopening and modifying any class, even built-in ones like String or Integer. While powerful for DSLs and testing, it can cause conflicts. Rails uses it extensively (ActiveSupport). Use refinements for scoped modifications.
How do blocks, procs, and lambdas differ?
Blocks are anonymous code between { } or do...end, passed to methods implicitly. Procs (Proc.new) are stored blocks with loose argument handling. Lambdas (-> {}) are strict procs that check arguments and return locally.
What is the Ruby convention for naming?
snake_case for methods and variables, CamelCase for classes and modules, SCREAMING_SNAKE for constants. Methods returning booleans end with ?, destructive methods end with !. Follow these conventions - Ruby developers rely on them.
Go from reference to real skills
Cheat sheets are great for quick lookups. Our in-depth courses take you from the fundamentals to professional-level mastery.
Browse all courses