ruby programming language(ch4-5)
Ch4
parallel assign
x,y,z = 1,2,3same asx,y,z = [1,2,3]orx,y,z=*[1,2,3](splat)- swap:
x,y = y,x(like python) - lvalues can only have one splat:
*x,y = 1,2,3[1,2],3x,y,*z = 1,*[2,3,4]1,2,[3,4]x,y,z = 1,[2,3]1,[2,3],nil, butx,y,z=1,*[2,3]1,2,3*on lvalue as compress, on rvalue as decompress
flip-flop
(1..10).each {|x| print x if x==3..x>=3}3 because..does evaluation and righthand expr check(to flop out) at same time(1..10).each {|x| print x if x==3...x>=3}34 because...waits evaluation first, then check and flop out
oneline expr
(expr) if (expr)- (in python
(expr) if (expr) else (expr)valid, while not in ruby)
Ch5
condition
if modifier
|
|
|
|
unless
- if-not
- no allow
elsif
case
case [when+] endno needbreak- can be used as expr value:
x = (case .. end)
while/until as modifier
expr while(until) expr- or as
if
iterate
- integral:
.upto,.downto,.times continous:
start.step(end, step).collect(like.map?) traversal and process each.selectout subset meet requirements,.rejectas inverse.injectas reduce
custom
yieldvalues to block as parameter, say invoke the block with yielded valuesif block_given?to determine whether invoke or not- return as enumerator:
self.to_enum(:yout_yield_method), which can then invoke.each, etc. - as external iterator:
loop {iterator.next}, which raise StopIteration
alter control flow
return: allow return multi values from block, but jumps out of current enclosing method, thus return values as method valuesbreak: likereturncan have a value, but jumps out of whole iteration but not method scopenext: allow return values, jumps out current iterationredo: restart current iteration, skipping checking the condition
exception
raise
raise "bad argument" if <cond>raise RuntimeError, "bad argument" if <cond>raise RuntimeError.new "bad argument" if <cond>raise RuntimeError.exception "bad argument" if <cond>
rescue
|
|
variables in rescue scope are visiable to rest after
rescue Exceptionrescue ArgumentError => erescue ArgumentError, TypeError => eor-match
as modifier: y = factorial(x) rescue 0, handles any StandardError and return the default follows rescue
BEGIN/END
BEGIN {..}executes before anything else only once without considering conditionsEND {..}consider conditions; first register(encounter), last execute; only once even in loop
thread
|
|
fiber
lightweight thread
normal
require 'fiber'.yieldtransfers control back to caller,.resumeto return
example:
|
|
diff with yield in iteration:
- fiber yields to caller
- iter yields to block
with arguments & return values
|
|
transfer
unlike thread, fibers must be explicitly scheduled via transfer
|
|
continuation
performs jump(goto)
take example:
|
|