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”
“#{con­cat­e}#­{na­tion}”
astrin­g.l­ength
astrin­g.e­mpty?
"­a,b­,c".s­pl­it(',')
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.first
,
foo.second
foo.length
foo.last == foo[-1]
foo.empty?
foo.in­clude?(x)
foo.sort
[
!
]
foo.sh­uffle
[
!
]
foo.re­verse
[
!
]
foo.push(x)
or
foo << x
foo.jo­in(­"­,")
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­wncase)
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["na­me"]
"­Joh­n"
foo = { name: "­Joh­n", id: "­JH" }
foo[:id]
"­JH"
foo.each do |key, value|
  puts "­#{k­ey.i­ns­pect} - #{value.inspect}"
end
:name - "­Joh­n"

:id - "­JH"
 

Ruby - Objects

anobje­ct.nil?
True or False
anobje­ct.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