Ruby Cheatsheet
Basics
Use this Ruby reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Running Ruby
ruby app.rb # run a file ruby -e 'puts 2+2' # run one expression irb # interactive Ruby shell ruby -c app.rb # syntax check only
Variables and Constants
Ruby variables are dynamically typed names bound to objects.
name = "Ada" count = 3 price = 9.99 active = true missing = nil PI = 3.14159 # constant by convention; reassignment warns $global = "avoid" # global variable @name = "field" # instance variable @@count = 0 # class variable, use sparingly
Core Types
| Type | Examples | Notes |
|---|---|---|
Integer | 42, -7, 0xff, 0b1010 | Arbitrary precision |
Float | 3.14, 1.0e-6 | IEEE decimal approximation |
String | "hi", 'hi', %q(hi) | Mutable text |
Symbol | :name, :admin | Immutable interned name |
Array | [1, 2, 3] | Ordered, mutable list |
Hash | { name: "Ada" } | Key-value map, insertion ordered |
Range | 1..5, 1...5 | Inclusive vs exclusive end |
Regexp | /\A[a-z]+\z/ | Pattern matching |
NilClass | nil | Absence of value |
TrueClass / FalseClass | true, false | Booleans |
Truthiness
Only false and nil are falsey. Everything else is truthy.
!!0 # true !!"" # true !![] # true !!nil # false !!false # false
Operators
1 + 2; 5 - 3; 4 * 2 7 / 3 # 2, integer division 7 / 3.0 # 2.3333333333333335 7.fdiv(3) # 2.3333333333333335 7 % 3 # 1 2 ** 8 # 256 x += 1; x -= 1; x *= 2; x /= 2 a == b # value equality a != b a < b; a <= b; a > b; a >= b a.equal?(b) # same object identity a.eql?(b) # hash-key equality semantics
String Literals and Interpolation
name = "Ada" "Hello, #{name}" # interpolation 'Hello, #{name}' # literal, no interpolation %Q(Hello, #{name}) # double-quoted style %q(Hello, #{name}) # single-quoted style <<~TEXT heredoc with indentation stripped TEXT
Common String Methods
s = " Ruby Language " s.strip # "Ruby Language" s.downcase # " ruby language " s.upcase s.include?("Ruby") s.start_with?(" R") s.end_with?(" ") s.split # ["Ruby", "Language"] s.gsub("Ruby", "Rails") s.delete("aeiou") s.chars # array of characters s.each_char { |ch| puts ch }
Conversions
"42".to_i # 42; forgiving, "42x" -> 42 Integer("42") # 42; strict, "42x" raises ArgumentError "3.14".to_f Float("3.14") 123.to_s :admin.to_s # "admin" "admin".to_sym # :admin [[:a, 1], [:b, 2]].to_h { a: 1 }.to_a # [[:a, 1]]