Show Menu
Cheatography

Ruby Cheat Sheet (DRAFT) by

Ruby Programming

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Arrays - Initia­lizing

[ 1 , 2 , 3 ] # => [1, 2, 3]
Array.new(2) # => [nil, nil]
Array.new(5) { |i| i * 5 } # => [0, 5, 10, 15, 20]
Array.new(2) { Array.n­ew(2) } # => [[nil, nil], [nil, nil]]
ary = [ ] # => []
ary = Array.new # => []
# initia­lizing array of strings on whitespace
%w(this that, and the other)
# => ["th­is", "­tha­t,", "­and­", "­the­", "­oth­er"]

Accessing and Assigning

ary = %w(ruby python perl php javascript c)
ary[0] # => "ruby"
ary[1] # => "python"
ary[2] # => "perl"
ary[3] # => "php"
ary[4] = 'ecmascript'
ary # => ["ru­by", "­pyt­hon­", "­per­l", "­php­", "­ecm­asc­rip­t", "­c"]
# negative indexes are applied from the end
ary[-1] # => "c"
ary[-2] # => "­ecm­asc­rip­t"
ary[-3] # => "­php­"
# first and last
ary.first # => "ruby"
ary.last # => "­c"
# subarrays give a range, or a start index and length
ary # => ["ru­by", "­pyt­hon­", "­per­l", "­php­", "­ecm­asc­rip­t", "c"]
ary[0..2] # => ["ru­by", "­pyt­hon­", "perl"]
ary[-3..-1] # => ["ph­p", "­ecm­asc­rip­t", "c"]
ary[2, 3] # => ["pe­rl", "­php­", "­ecm­asc­rip­t"]
# can replace a range of indexes with elements from an array (size doesn't need to match)
ary # => ["ru­by", "­pyt­hon­", "­per­l", "­php­", "ecmascript","c"]
ary[1..2] = [9,8,7,6,5,4,3,2,1]
ary # => ["ru­by",9 8,7,6,­5,4­,3,­2,1­,"ph­p,"e­cma­scr­ipt­", "c"]
ary = Array(­0..10) # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ary.insert(5,'five')
ary # => [0, 1, 2, 3, 4, "­fiv­e", 5, 6, 7, 8, 9, 10]

Sorting

^before = [3,6,3,0,8,235,-3]
after      = before.sort
before       # => [3, 6, 3, 0, 8, 235, -3]
after          # => [-3, 0, 3, 3, 6, 8, 235]^