/  14
 
Part 1
The Basics
A
RITHMETIC
2 + 32 – 32 * 32 / 3
P
RINTING
 
TO
 
THE
 
SCREEN
puts “Hello”print “Hello”p “Hello”x = “Hello”puts xprint xp x
G
ETTING
 
INPUT
 
FROM
 
THE
 
SCREEN
getsstring = gets
S
TRING
 
TO
 
NUMBER
 
CONVERSION
x = “100”.to_istring = “100”x = string.to_i
N
UMBER
 
TO
 
STRING
 
CONVERSION
x = 100.to_sx = 100string = x.to_s
C
OMPARING
 
TWO
 
VALUES
x == y
C
OMMENTING
#This is a comment!
F
ILE
 
HANDLING
File writing
fh = File.new(“filename.dat”, “w”)fh.puts x #x is imaginary variable herefh.close
File reading
fh = File.read(“filename.dat”)
E
XTERNAL
 
CODE
 
INCLUSION
require “filename.rb”
Or
load “filename.rb”
S
TRING
I
NTERPOLATION
x=1puts “x is equal to: #{x}”
E
MBEDDED
R
UBY
To embed Ruby code in HTML
<%#Ruby code in here%>
To 'print out' result of execution in HTML
<%=#Ruby code in here%>
C
ODE
B
LOCKS
Any code defined within {} or do end
{#code}
OR
do#code hereend
L
ITERAL
C
ONSTRUCTORS
 
TypeConstructorExampleString
“” or ''“abc” or 'abc'
Symbol
::symbol or:”symbol with spaces”
Array
[][1,2,3,4,5]
Hash
{}{New York=> NY“Oregon” => “OR”}
Range
.. or ...0..10 or 0...10
Regexp
///([a-z]+)/
S
YNTACTIC
S
UGAR
ArithmeticDefinitionCalling exampleSugared syntax
def + (x)obj.+(x)obj + xdef (x)obj.(x)obj xdef * (x)obj.*(x)obj * xdef / (x)obj./(x)obj / xdef % (x)obj.%(x)obj % x
Ruby Cheatbook by rubynerds.blogspot.com
Ruby Cheatbook
Based on Ruby for Railsby David BlackCompiled by Asyraf.rubynerds.blogspot.com
 
IncrementalsSugared syntaxHow ruby sees it
x += 1x = x + 1x = 1x = x 1x *= 2 x = x * 2x /= 2x = x / 2x %= 2x = x % 2
Get/Set/Append dataDefinitionCalling exampleSugared syntax
def [](x)obj.[](x)obj [ x]def []= (x,y)obj.[]=(x,y)obj [ x]= ydef << (x)obj.<<(x)obj << x
Comparison methodDefinitionCalling exampleSugared syntax
def ==(x)obj.==(x)obj == xdef > (x)obj.>(x)obj > xdef < (x)obj.<(x)obj < xdef >= (x)obj.>=(x)obj >= xdef <= (x)obj.<=(x)obj <= x
Case equality (for case/when)DefinitionCalling exampleSugared syntax
def === (x)obj.===(x)obj === x
B
ANG
 
METHODS
The bang methods are defined with an exclamation '!'.These methods are user-definable, however, by default,they usually mean that they, unlike their non-bangequivalents,
modify their receivers.
Examples:
str = “hello”puts str.upcase #output: HELLOputs str #output: helloputs str.upcase!#output: HELLOputs str #output: HELLO
Variables and Constants
C
ONSTANTS
Constants start with a capital letter
Constant = “Hi!”
C
ONSTANT
R
ESOLUTION
 
IN
N
ESTED
C
LASSES
/M
ODULES
Class MModule NClass OClass PX = 1endendendend
The constant is accessed by
puts M::N::O::P::X
V
ALUE
 
TO
 
VARIABLE
 
ASSIGNMENT
x = 1string = “Hello!”
G
LOBAL
V
ARIABLES
Defined with the $ sign
$gvar = “This is a global variable!”
I
NSTANCE
V
ARIABLES
Refer to Instance Variables in Classes
Methods
M
ETHOD
 
DEFINITION
def method1(x)value = x + 1return valueend
M
ETHOD
A
RGUMENTS
DefinitionDescription
def method(a,b,c)
Fixed number of arguments
def method(*a)
Variable number of args
def method(a=1,b=2)
Default value for arguments
def method(a,b=1,*c)
Combination argumentsNOTE: def method(a, *b, c) is not allowed! Arguments with* must always be at the end of the argument definition
B
OOLEAN
M
ETHODS
def ticket.available?#boolean evaluation hereend
S
ETTER
M
ETHODS
Refer to Setter Methods in ClassesRuby Cheatbook by rubynerds.blogspot.com
 
M
ETHOD
A
CCESS
R
ULES
Access RuleWho can access
Public
Other objects can access
Private
Only instances of object can accessmthd on itself (self only)
Protected
Only instances of object can accessmthd on each otherHere's 2 ways to define private/protected/#public methods(private example only)method 1:
Class Bakedef bake_cakeadd_eggstir_mixenddef add_eggenddef stir_mixend#private definitionprivate :add_egg, stir_mixend
method 2:
Class Bakedef bake_cakeadd_eggstir_mixendprivatedef add_eggenddef stir_mixendend
Objects
G
ENERIC
O
BJECT
obj = Object.new
O
BJECT
'
SINGLETON
'
METHOD
 
DEFINITION
def obj.method
puts “instance method definition”end#method callobj.method
D
EFAULT
O
BJECT
M
ETHODS
respond_to?Checks if methods by the name in argument are defined forthe object
obj.respond_to?(“method1”)
sendSends its arguments as 'message' to object (for methodcall)
x = “method1”obj.send(x)
object_idReturns specific id of object
obj.object_id
methodsReturns a list of methods defined for the object
obj.methods
Classes
C
LASS
D
EFINITION
class Ticket#class definitionend
C
LASS
O
BJECT
D
EFINITION
tix = Ticket.new
I
NSTANCE
M
ETHOD
D
EFINITION
class Ticketdef method#method definitionendendtix = Ticket.new#This is how instance methods are calledtix.method
C
LASS
M
ETHOD
D
EFINITION
class Ticket#This is a class definitiondef Ticket.cheapest(*tickets)#Class method definitionendend
I
NSTANCE
V
ARIABLES
Defined with @ in front
@venue = “City”
C
LASS
/O
BJECT
I
NITIALIZATION
class Ticketdef initialize(venue)@venue = venueend
Ruby Cheatbook by rubynerds.blogspot.com

Share & Embed

More from this user

Add a Comment

Characters: ...