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
Add a Comment