Ruby Cheat Sheet

posted in: ones and zeros | 0

Here’s another cheat sheet!

Ruby has so many easily-guessable method names that a cheat sheet almost seems superfluous, but soon I’ll start working on a Rails app for the first time in over a year so the review will be good for me 😉

This is a work-in-progress, the table of contents below is a bit of a to-do list – if I’ve added the section, there will be a link to it!

Last updated: 3/11/2019

Table of Contents

Data Types
Variable Declaration
Comments
Loops
Control Flow
Operators
Function Declaration
Classes
self
Strings
Symbols
Enumerable Methods
Arrays/Lists
Ranges
Hashes
Reserved Words
Dates
Regex
Language-Specific
Best Practices
Running a File
Loading a File
Interactive Command Line
Debugging/Tools
Resources

Data Types

Ruby doesn’t have primitive types, but the following concepts exist:

  • Numbers 42
  • Strings "hi"
  • Ranges 1..10
  • Symbols :hi
  • Arrays [1, 2, 3]
  • Hashes {"color": "blue"}
  • nil
  • Booleans true | false

Variable Declaration

local_variable = "hi"
$global_variable = "hej"
@@class_variable = "hola"
@instance_variable = "bonjour"
CONSTANT = "olá"  # start with uppercase letter

Comments

# I'm a comment

Loops

each returns the original, unchanged object:

(1..100).each do |counter|
  puts "iteration number #{counter}"
end

myHash.each do |key, value|
  puts "key: #{key}, value: #{value}"
end

myArray.each {|counter| puts counter}

times:

num.times do
  puts "hi"
end

map returns a new array with transformed elements:

myArrayOfStrings.map { |string| string.upcase }

while:

counter = 1
while counter < 10 do
  puts counter
  counter += 1
end

until:

counter = 1
until counter > 9 do
  puts counter
  counter += 1
end

Control Flow

if conditional1
  # do thing
elsif conditional2
  # do other thing
else
  # do something else
end

Operators

Arithmetic:

+
-
*
/
%
**

"100".to_i

Comparison:

==
!=
===     # for testing equality in the when clause of a case statement
.eql?   # checks for type and value
.equal? # checks for object id
<
>
<=
>=
!

Logical:

&&
||
!

Ternary:

condition ? a : b

Function Declaration

def func(a, b)
 a + b
end

Splat operator:

def colors(*array)
  array.each { |color| puts color }
end

Default arguments:

# named arguments
def func(a: 1, b: 2)
  a + b
end

# single star takes extra arguments into a hash
def func(a: 1, b: 2, *c)
  a + b
end

# double star takes all unknown named arguments into a hash
def func(a: 1, b: 2, **c)
  a + b
end

Classes

class Animal
  attr_reader :kind
  attr_accessor :says

  def initialize(kind, says="hello")
    @kind = kind
    @says = says
  end
end

jellie = Animal.new("cat")
jellie.says = "meow"

self

Default object; recipient of method calls that don’t specify the recipient.


# self => main

class MyClass
  # self => MyClass

  # can use self.method_name instead of ClassName.method_name:
  def self.class_method 
    # self => MyClass
  end

  def instance_method
    # self => instance of MyClass
  end
end

Strings

# interpolation calls .to_s on evaluated interpolation code
"Use double-quotes for interpolation: one plus one is #{ 1 + 1 }."

%q{Single-quote string}
%Q{Double-quote string}
%{Double-quote string}

my_string = "hello"
my_string[4]     #=> "o"
my_string[2, 4]  #=> "llo"

my_string[2..4]   #=> "llo"
my_string[2...4]  #=> "ll"
my_string[2..-1]  #=>"llo"

my_string["el"]  #=> "el"
my_string["hi"]  #=> nil

my_string[/e[lo ]+/]  #=> "ello"

my_string.slice("llo")  #=> "llo"
my_string.slice!("llo")  # removes "llo" from string
mystring  #=> "he" 

"hello" + "world"   #=> new string: "helloworld"
"hello" << "world"  #=> appends to original string

my_string.include?("hey")  #=> false
my_string.empty?           #=> false

"hello".size        #=> 5
"hello".count("h")  #=> 1
"hello".index("g")  #=> 0

"hello" == "hello"       #=> true
"hello".equal?("hello")  #=> false

.upcase
.downcase
.swapcase
.capitalize
.capitalize!
.chomp  # removes \n
.clear  #=> "" 

.to_i
.to_f

Enumerable Methods

Listed alphabetically:

:all?, :any?
:chunk, :chunk_while, :collect, :collect_concat, :count, :cycle, 
:detect, :drop, :drop_while, 
:each_cons, :each_entry, :each_slice, :each_with_index, :each_with_object, :entries, 
:find, :find_all, :find_index, :first, :flat_map
:grep, :grep_v, :group_by
:include?, :inject
:lazy
:map, :max, :max_by, :member?, :min, :min_by, :minmax, :minmax_by
:none?
:one? 
:partition
:reduce, :reject, :reverse_each
:select, :slice_after, :slice_before, :slice_when, :sort, :sort_by
:take, :take_while, :to_a, :to_h
:zip

Examples of common methods:

[1, 2, 12].any? {|n| (1..10).include?(n)}  #=> true

Arrays/Lists

my_array = [1, "two", [3]]
Array.new(3)  #=> [nil, nil, nil]
Array("hello")  #=> ["hello"]
%w{"hello world"}  #=> ['hello', 'world']
%i{ a b c }  #=> [:a, :b, :c]
a = [1, 2]
a[0]  #=> 1

a[2] = 3  
a  #=> [1, 2, 3]

a.unshift(0)  # add 0 to beginning of array
a << 4        # add 4 to end of array
a.push(5, 6)  # add 5 and 6 to end of array
a.shift       # remove from beginning return shifted
a.pop         # remove from end and return popped
a.pop(2)      # remove 2 items

[1, 2].concat([3, 4])  # changes receiving array
[1, 2].reverse         #=> [2, 1]
["1", "2"].join        #=> "12"
["1", "2"].join(" ")   #=> "1 2"
[1, 2, 3, 1, 1].uniq   #=> [1, 2, 3]
[1, 2, nil].compact    #=> [1, 2]

.size
.empty?
.include?(item)
.count(item)
.first(n)      # first n elements
.last(n)       # last n elements
.sample(n)     # n random elements

Hashes

{ "key" => "value" }
{ :key => "value" }
{ key: value }

Hash.new  #=> {}

Hash["key", "value", "key2", "value2"] 
#=> { "key" => "value", "key2" => "value2" }
Hash[["key", "value"], ["key2", "value2]]
#=> { "key" => "value", "key2" => "value2" }
my_hash = { "hello" => "world" }

my_hash["foo"] = "bar"
my_hash  #=> { "hello" => "world", "foo" => "bar" }

my_hash["hello"]            #=> "world"
my_hash["hi]                #=> nil (or specified default)
my_hash.fetch("hi")         # raises exception
my_hash.fetch("hi", "bye")  #=> "bye"

my_hash.values_at("hello", "foo")  #=> ["world", "bar"]

{ "hello" => "world" }.invert  #=> { "world" => "hello" } - only one unique value will persist because keys must be unique

.has_key?("hello")  #=> true
.include?("hello")  #=> true
.key?("hello")      #=> true
.member?("hello")   #=> true

.has_value?("world") #=> true
.value?("world") #=> true

.empty?  #=> false
.size    #=> 2
.clear   #=> {}

Loading a File

require "./filename.rb"  # in current directory
require_relative "filename"  # relative to current directory

Interactive Command Line

irb or irb --simple-prompt