Show Menu
Cheatography

Ruby and Rails (DRAFT) by

Ruby and Ruby on Rails Cheat Sheet

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

Ruby - Strings

"a string­"
'a string'
“Concate” + “nation”
“#{co­nca­te}­#{n­ati­on}”
astri­ng.l­ength
astri­ng.e­mpty?
"a,­b,c­".sp­lit­(',')
Result: [a,b,c]
Single quotes string, auto escape charac­ters.

Ruby - Array

foo = [a,b,c,d]
Used for all examples below
foo[n]
foo.f­irst, foo.s­econd
foo.l­ength
foo.last == foo[-1]
foo.e­mpty?
foo.i­ncl­ude­?(x)
foo.s­ort­[!]
foo.s­huf­fle­[!]
foo.r­eve­rse­[!]
foo.p­ush­(x) or foo << x
foo.j­oin­(",")
Result: "a, b, c, d"
foo[0..2]
Result: [a,b,c]
foo[1..-1]
Result: [b,c,d]
('a'..'d­').to_a == foo

Ruby - Block

3.times { puts "­foo­" }
Inline Block
(1..5­).each do |i|
  puts 2 * i
end
Multi Line Block
%w[A B C].map { |char| char.d­owncase }
%w[A B C].map­(&­:do­wnc­ase)
The last 2 lines result in an array of ["a­", "­b", "­c"]. The %w creates an array of string. The last one is a weird Ruby shortcut.
 

Ruby - Condit­ionals

puts "string is not empty" if !astring.empty?
puts "string is not empty" unless astring.empty?

if <expression>
  ...
else
  ...
end if

Ruby - Hash + Symbol

foo = { "­nam­e" => "­Joh­n", "­id" => "­JH" }
foo["n­ame­"]
"Jo­hn"
foo = { name: "­Joh­n", id: "­JH" }
foo[:id]
"JH­"
foo.each do |key, value|
  puts "­#{k­ey.i­ns­pect} - #{value.inspect}"
end
:name - "John"
:id - "­JH"
 

Ruby - Objects

anobj­ect.nil?
True or False
anobj­ect.to_s
To String

Ruby - Class

module BunchOfMethods
  def moduleMethod1
    ...
  end
  
  def moduleMethod2
    ...
  end
end

class MyClass < MySuperClass
  attr_accessor :attributeA, :attributeB

  def initialize(attributes = {})
    @attributeA  = attributes[:attributeA]
    @attributeB = attributes[:attributeB]
  end

  def NiceString
    "#{@attributeA} #{@attributeA}"
  end
end