Conditions
-
if-elsif-else
(basic):- basic condition control structure, will do anything you want.
- trick1: when you assign a value to a variable behind
if
- that variable can only be used in the multiline scheme.
- that variable cannot be used in the single line scheme.
- trick2: when you define a variable inside the conditional block.
- you can use it outside the conditional block
- when the condition is false, outside variable value is nil.
- both single line and multiline schemes can use this feature.
-
case-when-else
(switch):- has clear structure than the basic if-else structure.
- internally use the ruby triple equal operator
===
to compare. -
a === b
means "if 'a' describe a set, would 'b' be a member of that set?"- when range and element:
(1..5) === 3
- when class and class:
Object === String
- when class and object:
Object === 'string'
- when regex and string:
/foo/ === 'foobar'
- you can also rewrite
object === method
- when range and element:
- ternary-operator(terse):
- only use one line code, look so pretty :P_
- suit with simple statement, shouldn't be too complex.
- also use for assignment with condition:
a = condition ? b : c
-
&&
(and) vs||
(or):-
a && b
can convert to:b if a
-
a || b
can convert to:b if not a
- assign with default value:
x = a || b
- assign if not assigned before:
x ||= c
-
Loops
- iterators:
- (basic)
each, select, map, reduce...
- (numbers)
times, upto, downto, step...
- (basic)
- traditional-loop:
-
loop
: infinite loop, usebreak
to stop it.- use case: generate unique random keys.
-
- control-keywords:
-
break
: says quit immediately. -
next
: says loop immediately. -
redo
: says redoes that same loop over again. -
retry
: says starts the whole loop over from the beginning.
-