# top//a side-by-side reference sheet//

sheet one: [#version version] | [#grammar-execution grammar and execution] | [#var-expr variables and expressions] | [#arithmetic-logic arithmetic and logic] | [#strings strings] | [#regexes regexes] | [#dates-time dates and time] | [#arrays arrays] | [#dictionaries dictionaries] | [#functions functions] | [#execution-control execution control] | [#exceptions exceptions] | [#threads threads]

sheet two]: streams] | asynchronous events] | files] | file formats] | directories] | processes and environment] | option parsing] | libraries and namespaces] | objects] | reflection] | net and web] | databases] | unit tests] | debugging]

||||||||||~ # version[#version-note version]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# version-used[#version-used-note version used] _ @< >@||##gray|//6.11//##||##gray|//3.6//##||##gray|//7.0//##||##gray|//2.3//##|| ||# version[#version-note show version] _ @< >@||$ node @@–@@version||$ python -V _ $ python @@–@@version||$ php @@–@@version||$ ruby @@–@@version|| ||# implicit-prologue[#implicit-prologue-note implicit prologue] _ @< >@||##gray|@@//@@ npm install lodash## _ const _ = require(‘lodash’);||import os, re, sys||##gray|# sudo apt install php-mbstring##||##gray|//none//##|| ||||||||||~ # grammar-execution[#grammar-execution-note grammar and execution]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# interpreter[#interpreter-note interpreter] _ @< >@||$ node foo.js||$ python foo.py||$ php -f foo.php||$ ruby foo.rb|| ||# repl[#repl-note repl] _ @< >@||$ node||$ python||$ php -a||$ irb|| ||# cmd-line-program[#cmd-line-program-note command line program]||$ node -e “console.log(‘hi!’);”||$ python -c ‘print(“hi!”)’||$ php -r ‘echo “hi!\n”;’||$ ruby -e ‘puts “hi!”’|| ||# block-delimiters[#block-delimiters-note block delimiters] _ @< >@||{}||: ##gray|//and offside rule//##||{}||{} _ do end|| ||# statement-separator[#statement-separator-note statement separator] _ @< >@||##gray|//; or newline _ _ newline not separator inside (), [], {}, ““, ‘‘, or after binary operator _ _ newline sometimes not separator when following line would not parse as a valid statement//##||##gray|//newline or//## ; _ _ ##gray|//newlines not separators inside (), [], {}, triple quote literals, or after backslash: @@\@@//##||; _ _ ##gray|//statements must be semicolon terminated inside {}//##||##gray|//newline or//## ; _ _ ##gray|//newlines not separators inside (), [], {}, @@``@@, ‘‘, ““, or after binary operator or backslash: @@\@@//##|| ||# source-code-encoding[#source-code-encoding-note source code encoding]||##gray|//source is always UTF-8//##||##gray|//Python 3 source is UTF-8 by default; Python 2 source is US-ASCII//## _ _ ##gray|# -- coding: us-ascii --##||##gray|//none//##||##gray|//Ruby 2.0 source is UTF-8 by default//## _ _ ##gray|# -- coding: utf-8 --##|| ||# eol-comment[#eol-comment-note end-of-line comment] _ @< >@||##gray|@@//@@ comment##||##gray|# comment##|| ##gray|@@//@@ comment _

comment##|| ##gray|# comment##||

||# multiple-line-comment[#multiple-line-comment-note multiple line comment] _ @< >@||##gray|/* line _ another line /##||##gray|//use triple quote string literal://## _ _ ‘‘‘comment line _ another line’’’||##gray|/ comment line _ another line */##||##gray|=begin _ comment line _ another line _ =end##|| ||||||||||~ # var-expr[#var-expr-note variables and expressions]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# local-var[#local-var-note local variable] _ @< >@||##gray|@@//@@ new in ES6:## _ let x = 1; _ let y = 2, z = 3; _ _ ##gray|@@//@@ older alternative to let:## _ var x = 1; _ _ ##gray|@@//@@ let local scope is nearest _ @@//@@ enclosing block; var local scope _ @@//@@ is nearest function body. _ _ @@//@@ var variables are visible to all code _ @@//@@ in the function body; even code _ @@//@@ preceding the var statement.##||##gray|# in function body:## _ x = 1 _ y, z = 2, 3||##gray|# in function body:## _ $x = 1; _ list($y, $z) = [2, 3];||x = 1 _ y, z = 2, 3|| ||# file-scope-var[#file-scope-var-note file scope variable]||##gray|@@//@@ outside any function body:## _ let n = 1; _ _ incrFileVar () { n++; }||##gray|//none//##||##gray|//none//##||##gray|//none//##|| ||# global-var[#global-var-note global variable]||global.g = 1; _ _ incrGlobal () { global.g++; }||g = 1 _ _ def incr_global(): _ @<  >@global g _ @<  >@g += 1||$g = 1; _ _ function incr_global() { _ @<  >@global $g; _ @<  >@++$g; _ }||$g = 1 _ _ def incr_global _ @<  >@$g += 1 _ end|| ||# const[#const-note constant] _ @< >@||##gray|@@//@@ new in ES6## _ const PI = 3.14;||##gray|# uppercase identifiers _

constant by convention## _

PI = 3.14||define(“PI”, 3.14); _ _ const PI = 3.14;||##gray|# warning if capitalized _

identifier is reassigned## _

PI = 3.14|| ||# assignment[#assignment-note assignment] _ @< >@||v = 1;||##gray|# assignments can be chained _

but otherwise don’t return values:## _

v = 1||$v = 1;||v = 1|| ||# parallel-assignment[#parallel-assignment-note parallel assignment] _ @< >@||##gray|@@//@@ new in ES6:## _ let [x, y, z] = [1, 2, 3];||x, y, z = 1, 2, 3 _ _ ##gray|# raises ValueError:## _ x, y = 1, 2, 3 _ _ ##gray|# raises ValueError:## _ x, y, z = 1, 2||list($x, $y, $z) = [1 ,2, 3]; _ _ ##gray|# 3 is discarded:## _ list($x, $y) = [1, 2, 3]; _ _ ##gray|# $z set to NULL:## _ list($x, $y, $z) = [1, 2];||x, y, z = 1, 2, 3 _ _ ##gray|# 3 is discarded:## _ x, y = 1, 2, 3 _ _ ##gray|# z set to nil:## _ x, y, z = 1, 2|| ||# swap[#swap-note swap] _ @< >@||##gray|@@//@@ new in ES6:## _ [x, y] = [y, x];||x, y = y, x||list($x, $y) = [$y, $x];||x, y = y, x|| ||# compound-assignment[#compound-assignment-note compound assignment] _ ##gray|//arithmetic, string, logical, bit//##||+= -= *= /= ##gray|//none//## %= _ += _ ##gray|//none//## _ @@<<= >>= @@&= |= ^=||##gray|# do not return values:## _ += -= = /= @@//@@= %= @@*@@= _ += *= _ &= @@|@@= ^= _ @@<<= >>= @@&= |= ^=||+= -= = ##gray|//none//## /= %= @@*@@= _ .= ##gray|//none//## _ &= |= ##gray|//none//## _ @@<<= >>= @@&= |= ^=||+= -= = /= ##gray|//none//## %= @@*@@= _ += *= _ &&= @@||@@= ^= _ @@<<= >>= @@&= |= ^=|| ||# incr-decr[#incr-decr-note increment and decrement] _ @< >@||let x = 1; _ let y = ++x; _ let z = @@–@@y;||##gray|//none//##||$x = 1; _ $y = ++$x; _ $z = @@–@@$y;||x = 1 _ ##gray|# x and y not mutated:## _ y = x.succ _ z = y.pred|| ||# null[#null-note null] _ @< >@||null||None||NULL ##gray|# case insensitive##||nil|| ||# null-test[#null-test-note null test] _ @< >@||v === null||v is None||is_null($v) _ ! isset($v)||v == nil _ v.nil?|| ||# undef-var[#undef-var-note undefined variable] _ @< >@||##gray|//Evaluates as//## undefined _ _ ##gray|//Use the triple equality//## === ##gray|//operator to test for this value.//##||##gray|//raises//## NameError||##gray|//Evaluates as//## NULL||##gray|//raises//## NameError|| ||# conditional-expr[#conditional-expr-note conditional expression] _ @< >@||x > 0 ? x : -x||x if x > 0 else -x||$x > 0 ? $x : -$x||x > 0 ? x : -x|| ||||||||||~ # arithmetic-logic[#arithmetic-logic-note arithmetic and logic]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# true-false[#true-false-note true and false] _ @< >@||true false||True False||TRUE FALSE ##gray|# case insensitive##||true false|| ||# falsehoods[#falsehoods-note falsehoods] _ @< >@||false null undefined ‘‘ 0 NaN||False None 0 0.0 ‘‘ [] {}||FALSE NULL 0 0.0 ““ “0” []||false nil|| ||# logical-op[#logical-op-note logical operators] _ @< >@||@@&& ||@@ !||and or not||&& @@||@@ ! _ ##gray|//lower precedence://## _ and or xor||&& @@||@@ ! _ ##gray|//lower precedence://## _ and or not|| ||# relational-op[#relational-op-note relational operators] _ @< >@||@@===@@ !== < > >= <= _ _ ##gray|//perform type coercion://## _ @@==@@ !=||##gray|//relational operators are chainable://## _ == != > < >= <=||== != ##gray|//or//## <> > < >= <= _ ##gray|//no conversion://## === !==||== != > < >= <=|| ||# min-max[#min-max-note min and max] _ @< >@||Math.min(1, 2, 3) _ Math.max(1, 2, 3) _ _ Math.min.apply(Math, [1, 2, 3]) _ Math.max.apply(Math, [1, 2, 3])||min(1, 2, 3) _ max(1, 2, 3) _ _ min([1, 2, 3]) _ max([1, 2, 3])||min(1, 2, 3) _ max(1, 2, 3) _ $a = [1, 2, 3] _ min($a) _ max($a)||[1, 2, 3].min _ [1, 2, 3].max|| ||# arith-op[#arith-op-note arithmetic operators] _ ##gray|//addition, subtraction, multiplication, float division, quotient, remainder//##||+ - * / ##gray|//none//## %||+ - * / // % _ _ ##gray|//In Python 2, / performs integer division.//##||+ - * / ##gray|//none//## %||+ - * x.fdiv(y) / %|| ||# int-div[#int-div-note integer division] _ @< >@||Math.floor(22 / 7)||22 // 7||(int)(22 / 7) ||22 / 7|| ||# divmod[#divmod-note divmod] _ @< >@||##gray|//none//##||q, r = divmod(22, 7)||##gray|//none//##||q, r = 22.divmod(7)|| ||# int-div-zero[#int-div-zero-note integer division by zero] _ @< >@||##gray|//Returns Infinity, NaN, or -Infinity depending upon sign of dividend. _ _ There are literals for Infinity and NaN.//##||##gray|//raises// ZeroDivisionError##||##gray|//returns// FALSE //with warning//##||##gray|//raises// ZeroDivisionError##|| ||# float-div[#float-div-note float division] _ @< >@||22 / 7|| 22 / 7 _ _ ##gray|# Python 2:## _ float(22) / 7||22 / 7||22.to_f / 7 _ _ 22.fdiv(7)|| ||# float-div-zero[#float-div-zero-note float division by zero] _ @< >@||##gray|//same behavior as for integers//##||##gray|//raises// ZeroDivisionError##||##gray|//returns// FALSE //with warning//##||##gray|//returns// -Infinity, NaN, //or// Infinity##|| ||# power[#power-note power] _ @< >@||Math.pow(2, 32)||2 @@@@ 32||pow(2, 32)||2 @@@@ 32|| ||# sqrt[#sqrt-note sqrt]||Math.sqrt(2)||import math _ _ math.sqrt(2)||sqrt(2)||include Math _ _ sqrt(2)|| ||# sqrt-negative-one[#sqrt-negative-one-note sqrt -1] _ @< >@||NaN||##gray|# raises ValueError:## _ import math _ math.sqrt(-1) _ _ ##gray|# returns complex float:## _ import cmath _ cmath.sqrt(-1)||NaN||##gray|Math.sqrt(-1) raises Math::DomainError unless require ‘complex’ is in effect.## _ _ ##gray|(-1) ** 0.5 is (0+1.0i)##|| ||# transcendental-func[#transcendental-func-note transcendental functions] _ @< >@||Math.exp Math.log Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2||from math import exp, log, \ _ sin, cos, tan, asin, acos, atan, atan2||exp log sin cos tan asin acos atan atan2||include Math _ _ exp log sin cos tan asin acos atan atan2|| ||# transcendental-const[#transcendental-const-note transcendental constants] _ ##gray|//π and e//##||Math.PI _ Math.E||import math _ _ math.pi math.e||MPI ME||include Math _ _ PI E|| ||# float-truncation[#float-truncation-note float truncation] _ @< >@||##gray|//none//## _ Math.round(3.1) _ Math.floor(3.1) _ Math.ceil(3.1)||import math _ _ int(x) _ int(round(x)) _ math.ceil(x) _ math.floor(x)||(int)$x _ round($x) _ ceil($x) _ floor($x)||x.to_i _ x.round _ x.ceil _ x.floor|| ||# abs-val[#abs-val-note absolute value] _ @< >@||Math.abs(-3)||abs(x)||abs($x)||x.abs|| ||# int-overflow[#int-overflow-note integer overflow] _ @< >@||##gray|//all numbers are floats//##||##gray|//becomes arbitrary length integer of type// long##||##gray|//converted to float//##||##gray|//becomes arbitrary length integer of type// Bignum##|| ||# float-overflow[#float-overflow-note float overflow] _ @< >@||Infinity||##gray|//raises// OverflowError##||INF||Infinity|| ||# rational-construction[#rational-construction-note rational construction] _ @< >@||##gray|//none//##||from fractions import Fraction _ _ x = Fraction(22, 7)||##gray|//none//##||22 / 7r _ 22r / 7|| ||# rational-decomposition[#rational-decomposition-note rational decomposition] _ @< >@||##gray|//none//##||x.numerator _ x.denominator||##gray|//none//##||(22 / 7r).numerator _ (22 / 7r).denominator|| ||# complex-construction[#complex-construction-note complex construction] _ @< >@||##gray|//none//##||z = 1 + 1.414j||##gray|//none//##||z = 1 + 1.414i|| ||# complex-decomposition[#complex-decomposition-note complex decomposition] _ ##gray|//real and imaginary component, argument, absolute value, conjugate//##||##gray|//none//##||import cmath _ _ z.real _ z.imag _ cmath.phase(z) _ abs(z) _ z.conjugate()||##gray|//none//##||(1 + 3i).real _ (1 + 3i).imag _ (1 + 3i).arg _ (1 + 3i).abs _ (1 + 3i).conj|| ||# random-num[#random-num-note random number] _ ##gray|//uniform integer, uniform float, normal float//##||Math.floor(Math.random() * 100) _ Math.random() _ ##gray|//none//##||import random _ _ random.randint(0, 99) _ random.random() _ random.gauss(0, 1)||rand(0,99) _ lcg_value() _ ##gray|//none//##||rand(100) _ rand _ ##gray|//none//##|| ||# random-seed[#random-seed-note random seed] _ ##gray|//set, get, restore//##||##gray|//none//##||import random _ _ random.seed(17) _ seed = random.getstate() _ random.setstate(seed)||srand(17); _ _ ##gray|//none//##||srand(17) _ _ seed = srand _ srand(seed)|| ||# bit-op[#bit-op-note bit operators] _ @< >@||@<<< >> & | ^ ~>@||@<<< >> & | ^ ~>@||@<<< >> & | ^ ~>@||@<<< >> & | ^ ~>@|| ||# binary-octal-hex-literals[#binary-octal-hex-literals-note binary, octal, and hex literals]||##gray|//none//## _ 052 ##gray|@@//@@ deprecated## _ 0x2a||0b101010 _ 0o52@<  >@##gray|@@#@@ also 052 in Python 2## _ 0x2a||0b101010 _ 052 _ 0x2a||0b101010 _ 052 _ 0x2a|| ||# radix[#radix-note radix] _ ##gray|//convert integer to and from string with radix//##||(42).toString(7) _ parseInt(‘60’, 7)||##gray|//none//## _ int(‘60’, 7)||base_convert(“42”, 10, 7); _ baseconvert(“60”, 7, 10);||42.tos(7) _ “60”.to_i(7)|| ||||||||||~ # strings[#strings-note strings]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# str-type[#str-type-note string type] _ @< >@||String||str _ _ ##gray|# Python 2:## _ unicode||##gray|# array of bytes:## _ string||String|| ||# str-literal[#str-literal-note string literal] _ @< >@||’don\’t say “no”’ _ “don’t say "no"”||’don\’t say “no”’ _ “don’t say "no"” _ “don’t “ ‘say “no”’ _ _ ##gray|# Python 2 (and Python 3):## _ u’lorem’ _ u"ipsum”||"don’t say "no"” _ ‘don\’t say “no”’||"don’t say "no"” _ ‘don\’t say “no”’ _ “don’t “ ‘say “no”’|| ||# newline-in-str-literal[#newline-in-str-literal-note newline in literal] _ @< >@||##gray|@@//@@ backquote literals only:## _ @@@@first line _ second line@@@@ _ _ ##gray|@@//@@ Backslashes can be used to break _ @@//@@ long strings.##||##gray|# triple quote literals only:## _ ‘‘‘first line _ second line’’’ _ _ “““first line _ second line”””||’first line _ second line’ _ _ “first line _ second line”||’first line _ second line’ _ _ “first line _ second line”|| ||# str-literal-esc[#str-literal-esc-note literal escapes] _ @< >@||##gray|//single and double quotes://## _ \b \f \n \r \t \v \x##gray|//hh//## " \’ \ _ \u##gray|//hhhh//## \u{##gray|//hhhhh//##}||##gray|//newline//## \ \’ " \a \b \f \n \r \t \v ##gray|//ooo//## \x##gray|//hh//## \u##gray|//hhhh//## \U##gray|//hhhhhhhh//## _ _ ##gray|//In Python 2,// \u //and// \U //only available in string literals with// u //prefix//##||##gray|//double quoted://## _ \f \n \r \t \v \x##gray|//hh//## $ " \ ##gray|//ooo//## _ _ ##gray|//single quoted://## _ \’ \||##gray|//double quoted://## _ \a \b \c##gray|//x//## \e \f \n \r \s \t \v \x##gray|//hh//## ##gray|//ooo//## \u##gray|//hhhh//## \u{##gray|//hhhhh//##} _ _ ##gray|//single quoted://## _ \’ \|| ||# here-doc[#here-doc-note here document] _ @< >@||##gray|//none//##||##gray|//none//##||$word = “amet”; _ _ $s = @@<<<@@EOF _ lorem ipsum _ dolor sit $word _ EOF;||word = “amet” _ _ s = @@<<@@EOF _ lorem ipsum _ dolor sit #{word} _ EOF|| ||# var-interpolation[#var-interpolation-note variable interpolation] _ @< >@||let count = 3; _ let item = ‘ball’; _ let s = @@@@${count} ${item}s@@@@;||count = 3 _ item = ‘ball’ _ print(‘{count} {item}s’.format( _ @<  >@@@**@@locals())) _ _ ##gray|# Python 3.6:## _ print(f’{count} {item}s’)||$count = 3; _ $item = “ball”; _ echo “$count ${item}s\n”;||count = 3 _ item = “ball” _ puts “#{count} #{item}s”|| ||# expr-interpolation[#expr-interpolation-note expression interpolation]||@@@@1 + 1 = ${1 + 1}@@@@||’1 + 1 = {}’.format(1 + 1) _ _ ##gray|# Python 3.6:## _ f’1 + 1 = {1 + 1}’||##gray|//none//##||"1 + 1 = #{1 + 1}”|| ||# format-str[#format-str-note format string] _ @< >@||##gray|@@//@@ None; use string concatenation. _ @@//@@ Evaluates to “12.35”:## _ 12.3456.toFixed(2)||’lorem %s %d %f’ % (‘ipsum’, 13, 3.7) _ _ fmt = ‘lorem {0} {1} {2}’ _ fmt.format(‘ipsum’, 13, 3.7)||$fmt = “lorem %s %d %f”; _ sprintf($fmt, “ipsum”, 13, 3.7);||"lorem %s %d %f” % [“ipsum”, 13, 3.7]|| ||# mutable-str[#mutable-str-note are strings mutable?]||##gray|//no//##||##gray|//no//##||$s = “bar”; _ $s2 = $s; _ ##gray|# sets s to “baz”; s2 is unchanged:## _ $s[2] = “z”;||s = “bar” _ s2 = s _ ##gray|# sets s and s2 to “baz”:## _ s[2] = “z”|| ||# copy-str[#copy-str-note copy string]||##gray|//none//##||##gray|//none//##||$s2 = $s;||s = “bar” _ s2 = s.clone _ ##gray|# s2 is not altered:## _ s[2] = “z”|| ||# str-concat[#str-concat-note concatenate] _ @< >@||s = ‘Hello, ‘ + ‘World!’;||s = ‘Hello, ‘ _ s2 = s + ‘World!’ _ _ ##gray|# juxtaposition can be used to _

concatenate literals:## _

s2 = ‘Hello, ‘ “World!”||$s = “Hello, “; _ $s2 = $s . “World!”;||s = “Hello, “ _ s2 = s + “World!” _ _ ##gray|# juxtaposition can be used to _

concatenate literals:## _

s2 = “Hello, “ ‘World!’|| ||# str-replicate[#str-replicate-note replicate] _ @< >@||let hbar = .repeat(‘-’, 80);||hbar = ‘-’ * 80||$hbar = strrepeat(“-”, 80);||hbar = “-” * 80|| ||# translate-case[#translate-case-note translate case] _ ##gray|//to upper, to lower//##||’lorem’.toUpperCase() _ ‘LOREM’.toLowerCase()||’lorem’.upper() _ ‘LOREM’.lower()||mb_strtoupper(“lorem”) _ mb_strtolower(“LOREM”) _ ##gray|# strtoupper/strtolower are ASCII only##||"lorem”.upcase _ “LOREM”.downcase|| ||# capitalize[#capitalize-note capitalize] _ ##gray|//string, words//##||_.capitalize(‘lorem’); _ ##gray|//none//##||import string _ _ ‘lorem’.capitalize() _ string.capwords(‘lorem ipsum’)||##gray|# ASCII only:## _ ucfirst(strtolower(“lorem”)) _ ucwords(strtolower(“lorem ipsum”)) _ ##gray|# Unicode title case:## _ mbconvertcase(“lorem ipsum”, MBCASETITLE)||"lorem”.capitalize _ ##gray|//none//##|| ||# trim[#trim-note trim] _ ##gray|//both sides, left, right//##||’ lorem ‘.trim() _ ‘ lorem’.trimLeft() _ ‘lorem ‘.trimRight()||’ lorem ‘.strip() _ ‘ lorem’.lstrip() _ ‘lorem ‘.rstrip()||trim(“ lorem “) _ ltrim(“ lorem”) _ rtrim(“lorem “)||” lorem “.strip _ “ lorem”.lstrip _ “lorem “.rstrip|| ||# pad[#pad-note pad] _ ##gray|//on right, on left, centered//##||_.padStart(‘lorem’, 10) _ _.padEnd(‘lorem’, 10) _ _.pad(‘lorem’, 10)||’lorem’.ljust(10) _ ‘lorem’.rjust(10) _ ‘lorem’.center(10)||$s = “lorem”; _ $delta = strlen($s) - mb_strlen($s); _ str_pad($s, 10 + $delta) _ strpad(“$s, 10 + $delta, “ “, STRPAD_LEFT) _ strpad($s, 10 + $delta, “ “, STRPAD_BOTH)||"lorem”.ljust(10) _ “lorem”.rjust(10) _ “lorem”.center(10)|| ||# num-to-str[#num-to-str-note number to string] _ @< >@||’value: ‘ + 8||’value: ‘ + str(8)||"value: “ . 8||"value: “ + 8.to_s|| ||# fmt-float[#fmt-float-note format float]||’’ + Math.round(Math.PI * 100) / 100||import math _ _ ‘%.2f’ % math.pi _ ‘{:.3}’.format(math.pi) _ ##gray|# Python 3.6:## _ f’{math.pi:.{3}}’||numberformat(MPI, 2)||include Math _ _ ‘%.2f’ % PI _ “#{PI.round(2)}”|| ||# str-to-num[#str-to-num-note string to number] _ @< >@||7 + parseInt(‘12;, 10) _ 73.9 + parseFloat(‘.037’) _ _ ##gray|@@//@@ 12:## _ parseInt(‘12A’) _ ##gray|@@//@@ NaN:## _ parseInt(‘A’)||7 + int(‘12’) _ 73.9 + float(‘.037’) _ _ ##gray|# raises ValueError:## _ int(‘12A’) _ ##gray|# raises ValueError:## _ int(‘A’)||7 + “12” _ 73.9 + “.037” _ _ ##gray|# 12:## _ 0 + “12A” _ ##gray|# 0:## _ 0 + “A”||7 + “12”.to_i _ 73.9 + “.037”.to_f _ _ ##gray|# 12:## _ “12A”.to_i _ ##gray|# 0:## _ “A”.to_i|| ||# str-join[#str-join-note string join] _ @< >@||[‘do’, ‘re’, ‘mi’].join(‘ ‘)||’ ‘.join([‘do’, ‘re’, ‘mi’, ‘fa’]) _ _ ##gray|# raises TypeError:## _ ‘ ‘.join([1, 2, 3])||$a = [“do”, “re”, “mi”, “fa”]; _ implode(“ “, $a)||%w(do re mi fa).join(‘ ‘) _ _ ##gray|# implicitly converted to strings:## _ [1, 2, 3].join(‘ ‘)|| ||# split[#split-note split] _ @< >@||##gray|@@//@@ [ ‘do’, ‘re’, ‘‘, ‘mi’, ‘‘ ]:## _ ‘do re@<  >@mi ‘.split(‘ ‘) _ _ ##gray|@@//@@ [ ‘do’, ‘re’, ‘mi’, ‘‘ ]:## _ ‘do re@<  >@mi ‘.split(/\s+/)||##gray|# [‘do’, ‘re’, ‘‘, ‘mi’, ‘‘]:## _ ‘do re@<  >@mi ‘.split(‘ ‘) _ _ ##gray|# [‘do’, ‘re’, ‘mi’]:## _ ‘do re@<  >@mi ‘.split()||##gray|# [ “do”, “re”, ““, “mi”, ““ ]:## _ explode(“ “, “do re@<  >@mi “) _ _ ##gray|# [ “do”, “re”, “mi”, ““ ]:## _ preg_split(‘/\s+/’, “do re@<  >@mi “)||##gray|# [“do”, “re”, ““, “mi”]:## _ “do re@<  >@mi “.split(/ /) _ _ ##gray|# [“do”, “re”, “mi”]:## _ “do re@<  >@mi “.split|| ||# split-in-two[#split-in-two-note split in two] _ @< >@||’do re mi fa’.split(/\s+/, 2)||’do re mi fa’.split(None, 1)||pregsplit(‘/\s+/’, “do re mi fa”, 2)||"do re mi fa”.split(/\s+/, 2)|| ||# split-keep-delimiters[#split-keep-delimiters-note split and keep delimiters]||##gray|//none//##||re.split(‘(\s+)’, ‘do re mi fa’)||pregsplit(‘/(\s+)/’, “do re mi fa”, _ @<  >@NULL, PREGSPLITDELIM_CAPTURE)||"do re mi fa”.split(/(\s+)/)|| ||# prefix-suffix-test[#prefix-suffix-test-note prefix and suffix test]||’foobar’.startsWith(‘foo’) _ ‘foobar’.endsWith(‘bar’)||’foobar’.startswith(‘foo’) _ ‘foobar’.endswith(‘bar’)|| ||’foobar’.start_with?(‘foo’) _ ‘foobar’.end_with?(‘bar’)|| ||# str-len[#str-len-note length] _ @< >@||’lorem’.length||len(‘lorem’)||mb_strlen(“lorem”) _ ##gray|# strlen() counts bytes##||"lorem”.length _ “lorem”.size|| ||# index-substr[#index-substr-note index of substring] _ ##gray|//first, last//##||##gray|@@//@@ returns -1 if not found:## _ ‘lorem ipsum’.indexOf(‘ipsum’)||##gray|# raises ValueError if not found:## _ ‘do re re’.index(‘re’) _ ‘do re re’.rindex(‘re’) _ _ ##gray|# returns -1 if not found:## _ ‘do re re’.find(‘re’) _ ‘do re re’.rfind(‘re’) ||##gray|# returns FALSE if not found:## _ mb_strpos(“do re re”, “re”) _ mb_strrpos(“do re re”, “re”)||##gray|# returns nil if not found:## _ “do re re”.index(“re”) _ “do re re”.rindex(“re”)|| ||# extract-substr[#extract-substr-note extract substring] _ ##gray|//by start and length, by start and end, by successive starts//##||’lorem ipsum’.substr(6, 5) _ ‘lorem ipsum’.substring(6, 11)||##gray|//none//## _ ##gray|//none//## _ ‘lorem ipsum’[6:11]||mb_substr(“lorem ipsum”, 6, 5) _ ##gray|//none//## _ ##gray|//none//##||"lorem ipsum”[6, 5] _ “lorem ipsum”[6@@..@@10] _ “lorem ipsum”[6@@…@@11]|| ||# bytes-type[#bytes-type-note byte array type]||Buffer||bytes _ _ ##gray|# In Python 2, str also byte array type##||string||Array ##gray|//of//## Fixnum|| ||# bytes-to-str[#bytes-to-str-note byte array to string]||let a = Buffer.from([0xce, 0xbb]); _ let s = a.toString(‘utf-8’);||s = b’\xce\xbb’.decode(‘utf-8’)||##gray|//strings are byte arrays//##||a = “\u03bb”.bytes _ s = a.pack(“C*”).force_encoding(‘utf-8’)|| ||# str-to-bytes[#str-to-bytes-note string to byte array]||a = Buffer.from(‘\u03bb’)||a = ‘\u03bb’.encode(‘utf-8’) _ _ ##gray|# Python 2:## _ a = u’\u03bb’.encode(‘utf-8’)||##gray|//strings are byte arrays//##||a = “\u03bb”.bytes|| ||# lookup-char[#lookup-char-note character lookup]||’lorem ipsum’[6]||’lorem ipsum’[6]||mb_substr(“lorem ipsum”, 6, 1) _ ##gray|# byte lookup:## _ “lorem ipsum”[6]||"lorem ipsum”[6]|| ||# chr-ord[#chr-ord-note chr and ord] _ @< >@||String.fromCharCode(65) _ ‘A’.charCodeAt(0)||chr(65) _ ord(‘A’)||##gray|# ASCII only:## _ chr(65) _ ord(“A”)||65.chr(‘UTF-8’) _ “A”.ord|| ||# str-to-char-array[#str-to-char-array-note to array of characters] _ @< >@||’abcd’.split(‘‘)||list(‘abcd’)||str_split(“abcd”)||"abcd”.split(““)|| ||# translate-char[#translate-char-note translate characters] _ @< >@||##gray|//none//##||from string import ascii_lowercase _ _ ins = ascii_lowercase _ outs = ins[13:] + ins[:13] _ table = str.maketrans(ins, outs) _ ‘hello’.translate(table)||$ins = implode(range(“a”, “z”)); _ $outs = substr($ins, 13, 13) . _ @<  >@substr($ins, 0, 13); _ strtr(“hello”, $ins, $outs)||"hello”.tr(“a-z”, “n-za-m”)|| ||# delete-char[#delete-char-note delete characters]||##gray|//none//##||table = {ord(ch): None for ch in “aeiou”} _ “disemvowel me”.translate(table)||$vowels = str_split(“aeiou”); _ $s = “disemvowel me”; _ $s = str_replace($vowels, ““, $s);||"disemvowel me”.delete(“aeiou”)|| ||# squeeze-char[#squeeze-char-note squeeze characters]||##gray|//none//##||re.sub(‘(\s)+’, r’\1’, _ @<  >@’too@<   >@much@<   >@space’)||$s = “too@<   >@much@<   >@space”; _ $s = = preg_replace(‘/(\s)+/’, ‘\1’, $s);||"too@<   >@much@<   >@space”.squeeze(“ “)|| ||||||||||~ # regexes[#regexes-note regular expressions]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# regex-literal[#regex-literal-note literal, custom delimited literal]||/lorem|ipsum/||re.compile(r’lorem|ipsum’) _ ##gray|//none//##||’/lorem|ipsum/’ _ ‘(/etc/hosts)’||/lorem|ipsum/ _ %r(/etc/hosts) _ ##gray|# double quoted string escapes _

and #{} substitution can be used##||

||# ascii-char-class-abbrev[#ascii-char-class-abbrev-note ascii character class abbreviations]||.@<   >@[^\n] _ \d@<  >@[0-9] _ \D@<  >@[^0-9] _ \s@<  >@[ \t\r\n\f] _ \S@<  >@[^ \t\r\n\f] _ \w@<  >@[A-Za-z0-9_] _ \W@<  >@[^A-Za-z0-9_]||.@<   >@[^\n]@<  >@##gray|//with// re.S //modifier matches all chars//## _ \d@<  >@[0-9] _ \D@<  >@[^0-9] _ \s@<  >@[ \t\r\n\f] _ \S@<  >@[^ \t\r\n\f] _ \w@<  >@[A-Za-z0-9_] _ \W@<  >@[^A-Za-z0-9_] _ _ ##gray|//In Python 3, the above definitions are used when// re.A //is in effect.//##||.@<   >@[^\n] _ \d@<  >@[0-9] _ \D@<  >@[^0-9] _ \h@<  >@[ \t] _ \H@<  >@[^ \t] _ \s@<  >@[ \t\r\n\f] _ \S@<  >@[^ \t\r\n\f] _ \w@<  >@[A-Za-z0-9_] _ \W@<  >@[^A-Za-z0-9_]||.@<   >@[^\n]@<  >@##gray|//with// m //modifier matches all chars//## _ \d@<  >@[0-9] _ \D@<  >@[^0-9] _ \h@<  >@[0-9a-fA-F] _ \H@<  >@[^0-9a-fA-F] _ \s@<  >@[ \t\r\n\f] _ \S@<  >@[^ \t\r\n\f] _ \w@<  >@[A-Za-z0-9_] _ \W@<  >@[^A-Za-z0-9_]|| ||# unicode-char-class-abbrev[#unicode-char-class-abbrev-note unicode character class abbreviations]||##gray|//none//##||.@<   >@[^\n]@<  >@##gray|//with// re.S //modifier matches all chars//## _ \d@<  >@[##gray|//Nd//##]@<  >@##gray|Nd: //Number, decimal digit//## _ \D@<  >@[^##gray|//Nd//##] _ \s@<  >@[##gray|//Z//##\t\n\r\f\v\x1c\x1d\x1e\x1f\x85] _ \S@<  >@[^##gray|//Z//##\t\n\r\f\v\x1c\x1d\x1e\x1f\x85] _ \w [##gray|//LN//##_]@<  >@##gray|L: //Letter//; N: //Number//## _ \W [##gray|^//LN//##_] _ _ ##gray|//In Python 2, the above definitions are used when// re.U //is in effect.//##||##gray|//POSIX character classes such as// :alpha: //are available, but they match sets of ASCII characters. General category values (e.g.// \p{L}, \p{Lu}//) can be used. Morever, they can be used inside character classes (.e.g.// [\p{L}\p{N}]//).//##||. _ \p{Digit} _ \p{^Digit} _ \p{Space} _ \p{^Space} _ \p{Word} _ \p{^Word} _ _ ##gray|//POSIX character classes (e.g.// @@:alpha:@@//), general category values (e.g.// \p{L}, \p{Lu}//), and script names (e.g.// \p{Greek}) //also supported.//##|| ||# regex-anchors[#regex-anchors-note anchors] _ @< >@||^@<   >@##gray|//start of string or line with// m //modifier//## _ $@<   >@##gray|//end of string or line with// m //modifier//## _ \b@<  >@##gray|//word boundary:// \w\W //or// \W\w## _ \B@<  >@##gray|//non word boundary//##||^@<   >@##gray|//start of string or line with// re.M## _ $@<   >@##gray|//end of string or line with// re.M## _ \A@<  >@##gray|//start of string//## _ \b@<  >@##gray|//word boundary:// \w\W //or// \W\w## _ \B@<  >@##gray|//non word boundary//## _ \Z@<  >@##gray|//end of string//##||^@<   >@##gray|//start of string or line with// m //modifier//## _ $@<   >@##gray|//end of string or line with// m //modifier//## _ \A@<  >@##gray|//start of string//## _ \b@<  >@##gray|//word boundary:// \w\W //or// \W\w## _ \B@<  >@##gray|//non word boundary//## _ \z@<  >@##gray|//end of string//## _ \Z@<  >@##gray|//end of string, excluding final newline//##||^@<   >@##gray|//start of line//## _ $@<   >@##gray|//end of line//## _ \A@<  >@##gray|//start of string//## _ \b@<  >@##gray|//unicode-aware word boundary//## _ \B@<  >@##gray|//unicode-aware non word boundary//## _ \z@<  >@##gray|//end of string//## _ \Z@<  >@##gray|//end of string, excluding final newline//##|| ||# regex-test[#regex-test-note match test] _ @< >@||if (s.match(/1999/)) { _ @<  >@console.log(‘party!’); _ }||if re.search(‘1999’, s): _ @<  >@print(‘party!’)||if (preg_match(‘/1999/’, $s)) { _ @<  >@echo “party!\n”; _ }||if /1999/.match(s) _ @<  >@puts “party!” _ end|| ||# case-insensitive-regex[#case-insensitive-regex-note case insensitive match test] _ @< >@||’Lorem’.match(/lorem/i)||re.search(‘lorem’, ‘Lorem’, re.I)||preg_match(‘/lorem/i’, “Lorem”)||/lorem/i.match(“Lorem”)|| ||# regex-modifiers[#regex-modifiers-note modifiers] _ @< >@||g@<  >@##gray|//used for global substitution and scanning//## _ i@<  >@##gray|//make case insensitive//## _ m@<  >@##gray|//change meaning of// ^ //and// $## _ u@<  >@##gray|\u{} //syntax and astral character support//## _ y@<  >@##gray|//used to scan in loop//##||re.A@<  >@##gray|//change meaning of// \b \B \d \D \s \S \w \W## _ re.I@<  >@##gray|//make case insensitive//## _ re.M@<  >@##gray|//change meaning of// ^ //and// $## _ re.S@<  >@##gray|//change meaning of// .## _ re.X@<  >@##gray|//ignore whitespace outside char class//##||i@<  >@##gray|//make case insensitive//## _ m@<  >@##gray|//change meaning of// ^ //and// $## _ s@<  >@##gray|//change meaning of// .## _ x@<  >@##gray|//ignore whitespace outside char class//##||i@<  >@##gray|//make case insensitive//## _ o@<  >@##gray|//interpolate #{} in literal once//## _ m@<  >@##gray|//change meaning of// .## _ x@<  >@##gray|//ignore whitespace outside char class//##|| ||# subst[#subst-note substitution] _ @< >@||s = ‘do re mi mi mi’; _ s.replace(/mi/g, ‘ma’);||s = ‘do re mi mi mi’ _ s = re.compile(‘mi’).sub(‘ma’, s)||$s = “do re mi mi mi”; _ $s = preg_replace(‘/mi/’, “ma”, $s);||s = “do re mi mi mi” _ s.gsub!(/mi/, “ma”)|| ||# match-prematch-postmatch[#match-prematch-postmatch-note match, prematch, postmatch] _ @< >@||m = /\d{4}/.exec(s); _ if (m) { _ @<  >@match = m[0]; _ @<  >@##gray|@@//@@ no prematch or postmatch## _ }||m = re.search(‘\d{4}’, s) _ if m: _ @<  >@match = m.group() _ @<  >@prematch = s[0:m.start(0)] _ @<  >@postmatch = s[m.end(0):len(s)]||##gray|//none//##||m = /\d{4}/.match(s) _ if m _ @<  >@match = m[0] _ @<  >@prematch = m.pre_match _ @<  >@postmatch = m.post_match _ end|| ||# group-capture[#group-capture-note group capture] _ @< >@||rx = /^(\d{4})-(\d{2})-(\d{2})$/; _ m = rx.exec(‘2009-06-03’); _ yr = m[1]; _ mo = m[2]; _ dy = m[3];||rx = ‘(\d{4})-(\d{2})-(\d{2})’ _ m = re.search(rx, ‘2010-06-03’) _ yr, mo, dy = m.groups()||$s = “2010-06-03”; _ $rx = ‘/(\d{4})-(\d{2})-(\d{2})/’; _ preg_match($rx, $s, $m); _ list($_, $yr, $mo, $dy) = $m;||rx = /(\d{4})-(\d{2})-(\d{2})/ _ m = rx.match(“2010-06-03”) _ yr, mo, dy = m[1..3]|| ||# named-group-capture[#named-group-capture-note named group capture]||##gray|//none//##||rx = ‘^(?P.+).(?P.+)$’ _ m = re.search(rx, ‘foo.txt’) _ _ m.groupdict()[‘file’] _ m.groupdict()[‘suffix’]||$s = “foo.txt”; _ $rx = ‘/^(?P.+).(?P.+)$/’; _ preg_match($rx, $s, $m); _ _ $m[“file”] _ $m[“suffix”]||rx = /^(?.+).(?.+)$/ _ m = rx.match(‘foo.txt’) _ _ m[“file”] _ m[“suffix”]|| ||# scan[#scan-note scan] _ @< >@||let a = ‘dolor sit amet’.match(/\w+/g);||s = ‘dolor sit amet’ _ a = re.findall(‘\w+’, s)||$s = “dolor sit amet”; _ pregmatchall(‘/\w+/’, $s, $m); _ $a = $m[0];||a = “dolor sit amet”.scan(/\w+/)|| ||# backreference[#backreference-note backreference in match and substitution]||/(\w+) \1/.exec(‘do do’) _ _ ‘do re’.replace(/(\w+) (\w+)/, ‘$2 $1’)||##gray|//none//## _ _ rx = re.compile(‘(\w+) (\w+)’) _ rx.sub(r’\2 \1’, ‘do re’)||preg_match(‘/(\w+) \1/’, “do do”) _ _ $s = “do re”; _ $rx = ‘/(\w+) (\w+)/’; _ $s = preg_replace($rx, ‘\2 \1’, $s);||/(\w+) \1/.match(“do do”) _ _ “do re”.sub(/(\w+) (\w+)/, ‘\2 \1’)|| ||# recursive-regex[#recursive-regex-note recursive regex] _ @< >@||##gray|//none//##||##gray|//none//##||’/(([^()]|($R)))/’||/(?(([^()]|\g)*))/|| ||||||||||~ # dates-time[#dates-time-note dates and time]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# broken-down-datetime-type[#broken-down-datetime-type-note broken-down datetime type] _ @< >@||Date||datetime.datetime||DateTime||Time|| ||# current-datetime[#current-datetime-note current datetime]||let t = new Date();||import datetime _ _ t = datetime.datetime.now() _ utc = datetime.datetime.utcnow()||$t = new DateTime(“now”); _ $utc_tmz = new DateTimeZone(“UTC”); _ $utc = new DateTime(“now”, $utc_tmz);||t = Time.now _ utc = Time.now.utc|| ||# current-unix-epoch[#current-unix-epoch-note current unix epoch]||(new Date()).getTime() / 1000||import datetime _ _ t = datetime.datetime.now() _ epoch = int(t.strftime(“%s”))||$epoch = time();||epoch = Time.now.to_i|| ||# broken-down-datetime-to-unix-epoch[#broken-down-datetime-to-unix-epoch-note broken-down datetime to unix epoch]||Math.round(t.getTime() / 1000)||from datetime import datetime as dt _ _ epoch = int(t.strftime(“%s”))||$epoch = $t->getTimestamp();||epoch = t.to_i|| ||# unix-epoch-to-broken-down-datetime[#unix-epoch-to-broken-down-datetime-note unix epoch to broken-down datetime]||let epoch = 1315716177; _ let t2 = new Date(epoch * 1000);||t = dt.fromtimestamp(1304442000)||$t2 = new DateTime(); _ $t2->setTimestamp(1304442000);||t = Time.at(1304442000)|| ||# fmt-datetime[#fmt-datetime-note format datetime]||##gray|@@//@@ npm install moment## _ let moment = require(‘moment’); _ _ let t = moment(new Date()); _ let fmt = ‘YYYY-MM-DD HH:mm:ss’; _ console.log(t.format(fmt));||t.strftime(‘%Y-%m-%d %H:%M:%S’)||strftime(“%Y-%m-%d %H:%M:%S”, $epoch); _ date(“Y-m-d H:i:s”, $epoch); _ $t->format(“Y-m-d H:i:s”);||t.strftime(“%Y-%m-%d %H:%M:%S”)|| ||# parse-datetime[#parse-datetime-note parse datetime]||##gray|@@//@@ npm install moment## _ let moment = require(‘moment’); _ _ let fmt = ‘YYYY-MM-DD HH:mm:ss’; _ let s = ‘2011-05-03 10:00:00’; _ let t = moment(s, fmt);||from datetime import datetime _ _ s = ‘2011-05-03 10:00:00’ _ fmt = ‘%Y-%m-%d %H:%M:%S’ _ t = datetime.strptime(s, fmt)||$fmt = “Y-m-d H:i:s”; _ $s = “2011-05-03 10:00:00”; _ $t = DateTime::createFromFormat($fmt, _ @<  >@$s);||require ‘date’ _ _ s = “2011-05-03 10:00:00” _ fmt = “%Y-%m-%d %H:%M:%S” _ t = DateTime.strptime(s, fmt).to_time|| ||# parse-datetime-without-fmt[#parse-datetime-without-fmt-note parse datetime w/o format]||let t = new Date(‘July 7, 1999’);||##gray|# pip install python-dateutil## _ import dateutil.parser _ _ s = ‘July 7, 1999’ _ t = dateutil.parser.parse(s)||$epoch = strtotime(“July 7, 1999”);||require ‘date’ _ _ s = “July 7, 1999” _ t = Date.parse(s).to_time|| ||# date-parts[#date-parts-note date parts]||t.getFullYear() _ t.getMonth() + 1 _ t.getDate() ##gray|@@//@@ getDay() is day of week##||t.year _ t.month _ t.day||(int)$t->format(“Y”) _ (int)$t->format(“m”) _ (int)$t->format(“d”)||t.year _ t.month _ t.day|| ||# time-parts[#time-parts-note time parts]||t.getHours() _ t.getMinutes() _ t.getSeconds()||t.hour _ t.minute _ t.second||(int)$t->format(“H”) _ (int)$t->format(“i”) _ (int)$t->format(“s”)||t.hour _ t.min _ t.sec|| ||# build-datetime[#build-datetime-note build broken-down datetime]||let yr = 1999; _ let mo = 9; _ let dy = 10; _ let hr = 23; _ let mi = 30; _ let ss = 0; _ let t = new Date(yr, mo - 1, dy, _ @<  >@hr, mi, ss);||import datetime _ _ yr = 1999 _ mo = 9 _ dy = 10 _ hr = 23 _ mi = 30 _ ss = 0 _ t = datetime.datetime(yr, mo, dy, hr, mi, ss)|| ||yr = 1999 _ mo = 9 _ dy = 10 _ hr = 23 _ mi = 30 _ ss = 0 _ t = Time.new(yr, mo, dy, hr, mi, ss)|| ||# datetime-subtraction[#datetime-subtraction-note datetime subtraction]||##gray|number //containing time difference in milliseconds//##||##gray|datetime.timedelta //object//## _ _ ##gray|//use// total_seconds() //method to convert to float representing difference in seconds//##||##gray|# DateInterval object if diff method used:## _ $fmt = “Y-m-d H:i:s”; _ $s = “2011-05-03 10:00:00”; _ $then = DateTime::createFromFormat($fmt, $s); _ $now = new DateTime(“now”); _ $interval = $now->diff($then);||##gray|Float //containing time difference in seconds//##|| ||# add-duration[#add-duration-note add duration]||let t1 = new Date(); _ let delta = (10 * 60 + 3) * 1000; _ let t2 = new Date(t1.getTime() + delta);||import datetime _ _ delta = datetime.timedelta( _ @<  >@minutes=10, _ @<  >@seconds=3) _ t = datetime.datetime.now() + delta||$now = new DateTime(“now”); _ $now->add(new DateInterval(“PT10M3S”);||require ‘date/delta’ _ _ s = “10 min, 3 s” _ delta = Date::Delta.parse(s).in_secs _ t = Time.now + delta|| ||# local-tmz-determination[#local-tmz-determination-note local time zone determination]||##gray|TZ environment variable or host time zone##||##gray|//a// datetime //object has no time zone information unless a// tzinfo //object is provided when it is created//##||##gray|# DateTime objects can be instantiated _

without specifying the time zone _

if a default is set:## _

$s = “America/Los_Angeles”; _ datedefaulttimezone_set($s);||##gray|//if no time zone is specified the local time zone is used//##|| ||# nonlocal-tmz[#nonlocal-tmz-note nonlocal time zone]|| ||##gray|# pip install pytz## _ import pytz _ import datetime _ _ tmz = pytz.timezone(‘Asia/Tokyo’) _ utc = datetime.datetime.utcnow() _ utc_dt = datetime.datetime( _ @<  >@*utc.timetuple()[0:6], _ @<  >@tzinfo=pytz.utc) _ jpdt = utcdt.astimezone(tmz)|| ||##gray|# gem install tzinfo## _ require ‘tzinfo’ _ _ tmz = TZInfo::Timezone.get(“Asia/Tokyo”) _ jptime = tmz.utcto_local(Time.now.utc)|| ||# tmz-info[#tmz-info-note time zone info] _ _ ##gray|//name and UTC offset//##|| ||import time _ _ tm = time.localtime() _ @<  >@ _ time.tzname[tm.tm_isdst] _ (time.timezone / -3600) + tm.tmisdst||$tmz = datetimezone_get($t); _ _ timezonenameget($tmz); _ dateoffsetget($t) / 3600;||t.zone _ t.utc_offset / 3600|| ||# daylight-savings-test[#daylight-savings-test-note daylight savings test]||##gray|@@//@@ npm install moment## _ let moment = require(‘moment’); _ _ moment(new Date()).isDST()||import time _ _ tm = time.localtime() _ @<  >@ _ tm.tm_isdst||$t->format(“I”);||t.dst?|| ||# microseconds[#microseconds-note microseconds]||t.getMilliseconds() * 1000 _ _ ##gray|@@//@@ [sec, nanosec] since system boot:## _ process.hrtime()||t.microsecond||list($frac, $sec) = explode(“ “, microtime()); _ $usec = $frac * 1000 * 1000;||t.usec|| ||||||||||~ # arrays[#arrays-note arrays]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# array-literal[#array-literal-note literal] _ @< >@||a = [1, 2, 3, 4]||a = [1, 2, 3, 4]||$a = [1, 2, 3, 4]; _ _ ##gray|# older syntax:## _ $a = array(1, 2, 3, 4);||a = [1, 2, 3, 4] _ _ ##gray|# a = [‘do’, ‘re’, ‘mi’]## _ a = %w(do re mi)|| ||# array-size[#array-size-note size] _ @< >@||a.length||len(a)||count($a)||a.size _ a.length|| ||# array-empty[#array-empty-note empty test] _ @< >@||##gray|@@//@@ TypeError if a is null or undefined:## _ a.length === 0||##gray|# None tests as empty:## _ not a||##gray|# NULL tests as empty:## _ !$a||##gray|# NoMethodError if a is nil:## _ a.empty?|| ||# array-lookup[#array-lookup-note lookup] _ @< >@||a[0]||a[0] _ _ ##gray|# returns last element:## _ a[-1]||$a[0] _ _ ##gray|# PHP uses the same type for arrays and _

dictionaries; indices can be negative _

integers or strings##||a[0] _

_ ##gray|# returns last element:## _ a[-1]|| ||# array-update[#array-update-note update] _ @< >@||a[0] = ‘lorem’||a[0] = ‘lorem’ ||$a[0] = “lorem”;||a[0] = “lorem”|| ||# array-out-of-bounds[#array-out-of-bounds-note out-of-bounds behavior]||##gray|//returns// undefined##||a = [] _ ##gray|# raises IndexError:## _ a[10] _ ##gray|# raises IndexError:## _ a[10] = ‘lorem’||$a = []; _ ##gray|# evaluates as NULL:## _ $a[10]; _ ##gray|# increases array size to one:## _ $a[10] = “lorem”;||a = [] _ ##gray|# evaluates as nil:## _ a[10] _ ##gray|# increases array size to 11:## _ a[10] = “lorem”|| ||# array-element-index[#array-element-index-note element index] _ _ ##gray|//first and last occurrence//##||##gray|@@//@@ return -1 if not found:## _ [6, 7, 7, 8].indexOf(7) _ [6, 7, 7, 8].lastIndexOf(7)||a = [‘x’, ‘y’, ‘y’, ‘z’] _ _ ##gray|# raises ValueError if not found:## _ a.index(‘y’) _ ##gray|//none//##||$a = [“x”, “y”, “y”, “z”]; _ _ ##gray|# returns FALSE if not found:## _ $i = array_search(“y”, $a, TRUE); _ ##gray|//none//##||a = %w(x y y z) _ _ ##gray|# return nil if not found:## _ a.index(‘y’) _ a.rindex(‘y’)|| ||# array-slice[#array-slice-note slice] _ ##gray|//by endpoints, by length//## _ @< >@||##gray|@@//@@ select 3rd and 4th elements:## _ [‘a’, ‘b’, ‘c’, ‘d’].slice(2, 4) _ ##gray|//none//##||##gray|# select 3rd and 4th elements:## _ a[2:4] _ a[@@2:2@@ + 2]||##gray|# select 3rd and 4th elements:## _ ##gray|//none//## _ array_slice($a, 2, 2)||##gray|# select 3rd and 4th elements:## _ a[2..3] _ a[2, 2]|| ||# array-slice-to-end[#array-slice-to-end-note slice to end] _ @< >@||[‘a’, ‘b’, ‘c’, ‘d’].slice(1)||a[1:]||array_slice($a, 1)||a[1..-1]|| ||# array-back[#array-back-note manipulate back] _ @< >@||a = [6, 7, 8]; _ a.push(9); _ i = a.pop();||a = [6, 7, 8] _ a.append(9) _ a.pop()||$a = [6, 7, 8]; _ array_push($a, 9); _ $a[] = 9; ##gray|# same as array_push## _ array_pop($a);||a = [6, 7, 8] _ a.push(9) _ a @@<<@@ 9 ##gray|# same as push## _ a.pop|| ||# array-front[#array-front-note manipulate front] _ @< >@||a = [6, 7, 8]; _ a.unshift(5); _ i = a.shift();||a = [6, 7, 8] _ a.insert(0, 5) _ a.pop(0)||$a = [6, 7, 8]; _ array_unshift($a, 5); _ array_shift($a);||a = [6, 7, 8] _ a.unshift(5) _ a.shift|| ||# array-concatenation[#array-concatenation-note concatenate]||a = [1, 2, 3].concat([4, 5, 6]);||a = [1, 2, 3] _ a2 = a + [4, 5, 6] _ a.extend([4, 5, 6])||$a = [1, 2, 3]; _ $a2 = array_merge($a, [4, 5, 6]); _ $a = array_merge($a, [4, 5, 6]);||a = [1, 2, 3] _ a2 = a + [4, 5, 6] _ a.concat([4, 5, 6])|| ||# replicate-array[#replicate-array-note replicate]||Array(10).fill(null)||a = [None] * 10 _ a = [None for i in range(0, 10)]||$a = array_fill(0, 10, NULL);||a = [nil] * 10 _ a = Array.new(10, nil)|| ||# array-copy[#array-copy-note copy] _ ##gray|//address copy, shallow copy, deep copy//##||a = [1, 2, [3, 4]]; _ a2 = a; _ a3 = a.slice(0); _ a4 = JSON.parse(JSON.stringify(a));||import copy _ _ a = [1,2,[3,4]] _ a2 = a _ a3 = list(a) _ a4 = copy.deepcopy(a)||$a = [1, 2, [3, 4]]; _ $a2 =& $a; _ ##gray|//none//## _ $a4 = $a;||a = [1,2,[3,4]] _ a2 = a _ a3 = a.dup _ a4 = Marshal.load(Marshal.dump(a))|| ||# array-as-func-arg[#array-as-func-arg-note array as function argument]||##gray|//parameter contains address copy//##||##gray|//parameter contains address copy//##||##gray|//parameter contains deep copy//##||##gray|//parameter contains address copy//##|| ||# iterate-over-array[#iterate-over-array-note iterate over elements] _ @< >@||[6, 7, 8].forEach((n) => { _ @<  >@console.log(n); _ }); _ _ ##gray|@@//@@ new in ES6:## _ for (let n of [6, 7, 8]) { _ @<  >@console.log(n); _ }||for i in [1, 2, 3]: _ @<  >@print(i)||foreach ([1, 2, 3] as $i) { _ @<  >@echo “$i\n”; _ }||[1, 2, 3].each { |i| puts i }|| ||# indexed-array-iteration[#indexed-array-iteration-note iterate over indices and elements]||for (let i = 0; i < a.length; ++i) { _ @<  >@console.log(a[i]); _ } _ _ ##gray|@@//@@ indices not guaranteed to be in order:## _ for (let i in a) { _ @<  >@console.log(a[i]); _ }||a = [‘do’, ‘re’, ‘mi’, ‘fa’] _ for i, s in enumerate(a): _ @<  >@print(‘%s at index %d’ % (s, i))||$a = [“do”, “re”, “mi” “fa”]; _ foreach ($a as $i => $s) { _ @<  >@echo “$s at index $i\n”; _ }||a = %w(do re mi fa) _ a.eachwithindex do |s, i| _ @<  >@puts “#{s} at index #{i}” _ end|| ||# range-iteration[#range-iteration-note iterate over range]||##gray|//not space efficient; use C-style for loop//##||##gray|# use range() in Python 3:## _ for i in xrange(1, 1000001): _ @<  >@##gray|//code//##||##gray|//not space efficient; use C-style for loop//##||(1..1000000).each do |i| _ @<  >@##gray|//code//## _ end|| ||# range-array[#range-array-note instantiate range as array]||let a = _.range(1, 11);||a = range(1, 11) _ ##gray|//Python 3://## _ a = list(range(1, 11))||$a = range(1, 10);||a = (1..10).to_a|| ||# array-reverse[#array-reverse-note reverse] _ ##gray|//non-destructive, in-place//##||let a = [1, 2, 3]; _ _ let a2 = a.slice(0).reverse(); _ a.reverse();||a = [1, 2, 3] _ _ a[::-1] _ a.reverse()||$a = [1, 2, 3]; _ _ array_reverse($a); _ $a = array_reverse($a);||a = [1, 2, 3] _ _ a.reverse _ a.reverse!|| ||# array-sort[#array-sort-note sort] _ ##gray|//non-destructive, _ in-place, _ custom comparision//##||let a = [3, 1, 4, 2]; _ _ let a2 = a.slice(0).sort(); _ a.sort();||a = [‘b’, ‘A’, ‘a’, ‘B’] _ _ sorted(a) _ a.sort() _ ##gray|# custom binary comparision _

removed from Python 3:## _

a.sort(key=str.lower)||$a = [“b”, “A”, “a”, “B”]; _ _ ##gray|//none//## _ sort($a); _ ##gray|//none, but// usort //sorts in place//##||a = %w(b A a B) _ _ a.sort _ a.sort! _ a.sort do |x, y| _ @<  >@x.downcase <=> y.downcase _ end|| ||# array-dedupe[#array-dedupe-note dedupe] _ ##gray|//non-destructive, in-place//##||let a = [1, 2, 2, 3]; _ _ let a2 = _.uniq(a); _ a = _.uniq(a);||a = [1, 2, 2, 3] _ _ a2 = list(set(a)) _ a = list(set(a))||$a = [1, 2, 2, 3]; _ _ $a2 = array_unique($a); _ $a = array_unique($a);||a = [1, 2, 2, 3] _ _ a2 = a.uniq _ a.uniq!|| ||# membership[#membership-note membership] _ @< >@||a.includes(7)||7 in a||in_array(7, $a)||a.include?(7)|| ||# intersection[#intersection-note intersection] _ @< >@||_.intersection([1, 2], [2, 3, 4])||{1, 2} & {2, 3, 4}|| $a = [1, 2]; _ $b = [2, 3, 4] _ array_intersect($a, $b)||[1, 2] & [2 ,3, 4]|| ||# union[#union-note union] _ @< >@||_.union([1, 2], [2, 3, 4])||{1, 2} | {2, 3, 4}||$a1 = [1, 2]; _ $a2 = [2, 3, 4]; _ arrayunique(arraymerge($a1, $a2))||[1, 2] | [2, 3, 4]|| ||# set-diff[#set-diff-note relative complement, symmetric difference]||_.difference([1, 2, 3], [2]) _ ##gray|//none//##||{1, 2, 3} - {2} _ {1, 2} ^ {2, 3, 4}||$a1 = [1, 2, 3]; _ $a2 = [2]; _ arrayvalues(arraydiff($a1, $a2)) _ ##gray|//none//##||require ‘set’ _ _ [1, 2, 3] - [2] _ Set[1, 2] ^ Set[2 ,3, 4]|| ||# map[#map-note map] _ @< >@||##gray|@@//@@ callback gets 3 args: _ @@//@@ value, index, array## _ a.map((x) => x * x)||map(lambda x: x * x, [1, 2, 3]) _ ##gray|# or use list comprehension:## _ [x * x for x in [1, 2, 3]]||array_map(function ($x) { _ @<  >@@<  >@return $x * $x; _ @<  >@}, [1, 2, 3])||[1, 2, 3].map { |o| o * o }|| ||# filter[#filter-note filter] _ @< >@||a.filter((x) => x > 1) ||filter(lambda x: x > 1, [1, 2, 3]) _ ##gray|# or use list comprehension:## _ [x for x in [1, 2, 3] if x > 1]||array_filter([1, 2, 3], _ @<  >@function ($x) { _ @<  >@@<  >@return $x>1; _ @<  >@})||[1, 2, 3].select { |o| o > 1 }|| ||# reduce[#reduce-note reduce] _ @< >@||a.reduce((m, o) => m + o, 0)||##gray|# import needed in Python 3 only## _ from functools import reduce _ _ reduce(lambda x, y: x + y, [1, 2, 3], 0)||array_reduce([1, 2, 3], _ @<  >@function($x,$y) { _ @<  >@@<  >@return $x + $y; _ @<  >@}, 0)||[1, 2, 3].inject(0) { |m, o| m + o }|| ||# universal-existential-test[#universal-existential-test-note universal and existential tests] _ @< >@||let a = [1, 2, 3, 4]; _ _ a.every((n) => n % 2 === 0) _ a.some((n) => n % 2 === 0)||all(i % 2 == 0 for i in [1, 2, 3, 4]) _ any(i % 2 == 0 for i in [1, 2, 3, 4])||##gray|//use array_filter//##||[1, 2, 3, 4].all? {|i| i.even? } _ [1, 2, 3, 4].any? {|i| i.even? }|| ||# shuffle-sample[#shuffle-sample-note shuffle and sample]||let a = [1, 2, 3, 4]; _ _ a = _.shuffle(a); _ let samp = _.sampleSize([1, 2, 3, 4], 2);||from random import shuffle, sample _ _ a = [1, 2, 3, 4] _ shuffle(a) _ samp = sample([1, 2, 3, 4], 2)||$a = [1, 2, 3, 4]; _ _ shuffle($a); _ $samp = array_rand(|[1, 2, 3, 4], 2);||[1, 2, 3, 4].shuffle! _ samp = [1, 2, 3, 4].sample(2)|| ||# flatten[#flatten-note flatten] _ ##gray|//one level, completely//##||let a = [1, [2, [3, 4]]]; _ _ let a2 = _.flatten(a); _ let a3 = _.flattenDeep(a);||##gray|//none//##||##gray|//none//##||a = [1, [2, [3, 4]]] _ a2 = a.flatten(1) _ a3 = a.flatten|| ||# zip[#zip-note zip] _ @< >@||let a = _.zip([1, 2, 3], [‘a’, ‘b’, ‘c’]); _ _ ##gray|@@//@@ shorter array padded with undefined:## _ _.zip([1, 2, 3], [‘a’, ‘b’])||list(zip([1, 2, 3], [‘a’, ‘b’, ‘c’])) _ _ ##gray|# extras in longer array dropped:## _ list(zip([1, 2, 3], [‘a’, ‘b’]))||$a = array_map(NULL, _ @<  >@[1, 2, 3], _ @<  >@[“a”, “b”, “c”]); _ _ ##gray|# shorter array padded with NULLs##||[1, 2, 3].zip([“a”, “b”, “c”]) _ _ ##gray|# shorter array padded with nil:## _ [1, 2, 3].zip([“a”, “b”])|| ||||||||||~ # dictionaries[#dictionaries-note dictionaries]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# dict-literal[#dict-literal-note literal] _ @< >@||d = {t: 1, f: 0}; _ ##gray|@@//@@ keys do not need to be quoted if they _ @@//@@ are a legal JavaScript variable name _ @@//@@ and not a reserved word##||d = {’t’: 1, ‘f’: 0}||$d = [“t” => 1, “f” => 0]; _ _ ##gray|# older syntax:## _ $d = array(“t” => 1, “f” => 0);||d = {’t’ => 1, ‘f’ => 0} _ _ ##gray|# keys are symbols:## _ symboltoint = {t: 1, f: 0}|| ||# dict-size[#dict-size-note size] _ @< >@||_.size(d) _ Object.getOwnPropertyNames(d).length||len(d)||count($d)||d.size _ d.length|| ||# dict-lookup[#dict-lookup-note lookup] _ @< >@||d.hasOwnProperty(“t”) ? d[“t”] : undefined _ d.hasOwnProperty(“t”) ? d.t : undefined _ _ ##gray|@@//@@ JavaScript dictionaries are objects _ @@//@@ and inherit properties from Object.##||d[‘t’]||$d[“t”]||d[‘t’]|| ||# dict-update[#dict-update-note update]||d[‘t’] = 2; _ d.t = 2;||d[‘t’] = 2 _ _ ##gray|# provide default to avoid KeyError:## _ d.get(‘t’, None)||$d[“t”] = 2;||d[‘t’] = 2|| ||# dict-missing-key[#dict-missing-key-note missing key behavior] _ @< >@||let d = {}; _ ##gray|@@//@@ undefined:## _ d[“lorem”]; _ ##gray|@@//@@ adds key/value pair:## _ d[“lorem”] = “ipsum”; ||d = {} _ ##gray|# raises KeyError:## _ d[‘lorem’] _ ##gray|# adds key/value pair:## _ d[‘lorem’] = ‘ipsum’||$d = []; _ ##gray|# NULL:## _ $d[“lorem”]; _ ##gray|# adds key/value pair:## _ $d[“lorem”] = “ipsum”;||d = {} _ ##gray|# nil:## _ d[‘lorem’] _ ##gray|# adds key/value pair:## _ d[‘lorem’] = ‘ipsum’|| ||# dict-key-check[#dict-key-check-note is key present] _ @< >@||d.hasOwnProperty(“t”);||’y’ in d||arraykeyexists(“y”, $d);||d.key?(‘y’)|| ||# dict-delete[#dict-delete-note delete]||delete d[“t”]; _ delete d.t;||d = {1: True, 0: False} _ del d[1]||$d = [1 => “t”, 0 => “f”]; _ unset($d[1]);||d = {1 => true, 0 => false} _ d.delete(1)|| ||# dict-assoc-array[#dict-assoc-array-note from array of pairs, from even length array]||let a = [[‘a’, 1], [‘b’, 2], [‘c’, 3]]; _ let d = _.fromPairs(a); _ _ ##gray|//none//##||a = [[‘a’, 1], [‘b’, 2], [‘c’, 3]] _ d = dict(a) _ _ a = [‘a’, 1, ‘b’, 2, ‘c’, 3] _ d = dict(zip(a[::2], a[1::2]))|| ||a = [[‘a’, 1], [‘b’, 2], [‘c’, 3]] _ d = Hash[a] _ _ a = [‘a’, 1, ‘b’, 2, ‘c’, 3] _ d = Hash[*a]|| ||# dict-merge[#dict-merge-note merge]||let d1 = {a: 1, b: 2}; _ let d2 = {b: 3, c: 4}; _ ##gray|@@//@@ d2 overwrites shared keys in d1:## _ d1 = _.assignIn(d1, d2);||d1 = {’a’: 1, ‘b’: 2} _ d2 = {’b’: 3, ‘c’: 4} _ d1.update(d2)||$d1 = [“a” => 1, “b” => 2]; _ $d2 = [“b” => 3, “c” => 4]; _ $d1 = array_merge($d1, $d2);||d1 = {’a’ => 1, ‘b’ => 2} _ d2 = {’b’ => 3, ‘c’ => 4} _ d1.merge!(d2)|| ||# dict-invert[#dict-invert-note invert]||let let2num = {t: 1, f: 0}; _ let num2let = .invert(let2num);||tonum = {’t’: 1, ‘f’: 0} _ ##gray|# dict comprehensions added in 2.7:## _ to_let = {v: k for k, v _ @<  >@in tonum.items()}||$tonum = [“t” => 1, “f” => 0]; _ $tolet = arrayflip($tonum);||tonum = {’t’ => 1, ‘f’ => 0} _ tolet = tonum.invert|| ||# dict-iter[#dict-iter-note iterate] _ @< >@||for (let k in d) { _ @<  >@console.log(@@@@value at ${k} is ${d[k]}@@@@); _ }||for k, v in d.items(): _ @<  >@print(‘value at {} is {}’.format(k, v) _ _ ##gray|# Python 2: use iteritems()##||foreach ($d as $k => $v) { _ @<  >@echo “value at ${k} is ${v}”; _ }||d.each do |k,v| _ @<  >@puts “value at #{k} is #{v}” _ end|| ||# dict-key-val[#dict-key-val-note keys and values as arrays]||Object.keys(d) _ _.values(d)||list(d.keys()) _ list(d.values()) _ _ ##gray|# keys() and values return iterators _

in Python 3 and lists in Python 2##||array_keys($d) _

array_values($d)||d.keys _ d.values|| ||# dict-sort-values[#dict-sort-values-note sort by values]||let cmp = (a, b) => a[1] - b[1]; _ let d = {t: 1, f: 0}; _ _ for (let p of _.toPairs(d).sort(cmp)) { _ @<  >@console.log(p); _ }||from operator import itemgetter _ _ pairs = sorted(d.items(), key=itemgetter(1)) _ _ for k, v in pairs: _ @<  >@print(‘{}: {}’.format(k, v))||asort($d); _ _ foreach ($d as $k => $v) { _ @<  >@print “$k: $v\n”; _ }||d.sort_by { |k, v| v }.each do |k, v| _ @<  >@puts “#{k}: #{v}” _ end|| ||# dict-default-val[#dict-default-val-note default value, computed value]||##gray|//none//##||from collections import defaultdict _ _ counts = defaultdict(lambda: 0) _ counts[‘foo’] += 1 _ _ class Factorial(dict): _ @<  >@def @@missing@@(self, k): _ @<  >@@<  >@if k > 1: _ @<  >@@<  >@@<  >@return k * self[k-1] _ @<  >@@<  >@else: _ @<  >@@<  >@@<  >@return 1 _ _ factorial = Factorial()||$counts = []; _ $counts[‘foo’] += 1; _ _ ##gray|# For computed values and defaults other than _

zero or empty string, extend ArrayObject.##||counts = Hash.new(0) _

counts[‘foo’] += 1 _ _ factorial = Hash.new do |h,k| _ @<  >@k > 1 ? k * h[k-1] : 1 _ end|| ||||||||||~ # functions[#functions-note functions]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# def-func[#def-func-note define] _ @< >@||function add3 (x1, x2, x3) { _ @<  >@return x1 + x2 + x3; _ }||def add3(x1, x2, x3): _ @<  >@return x1 + x2 + x3||function add3($x1, $x2, $x3) _ { _ @<  >@return $x1 + $x2 + $x3; _ }||def add3(x1, x2, x3) _ @<  >@x1 + x2 + x3 _ end _ _ ##gray|# parens are optional and customarily _

omitted when defining functions _

with no parameters##||

||# invoke-func[#invoke-func-note invoke]||add3(1, 2, 3)||add3(1, 2, 3)||add3(1, 2, 3); _ _ ##gray|# function names are case insensitive:## _ ADD3(1, 2, 3);||add3(1, 2, 3) _ _ ##gray|# parens are optional:## _ add3 1, 2, 3|| ||# missing-arg[#missing-arg-note missing argument behavior] _ @< >@||##gray|//set to// undefined##||##gray|//raises// TypeError //if number of arguments doesn’t match function arity//##||##gray|//set to// NULL //with warning//##||##gray|//raises// ArgumentError //if number of arguments doesn’t match function arity//##|| ||# extra-arg[#extra-arg-note extra argument behavior] _ @< >@||##gray|//ignored//##||##gray|//raises// TypeError //if number of arguments doesn’t match function arity//##||##gray|//ignored//##||##gray|//raises// ArgumentError //if number of arguments doesn’t match function arity//##|| ||# default-arg[#default-arg-note default argument] _ @< >@||##gray|@@//@@ new in ES6:## _ function myLog (x, base = 10) { _ @<  >@return Math.log(x) / Math.log(base); _ }||import math _ _ def my_log(x, base=10): _ @<  >@return math.log(x) / math.log(base) _ _ my_log(42) _ mylog(42, math.e)||function mylog($x, $base=10) _ { _ @<  >@return log($x) / log($base); _ } _ _ my_log(42); _ mylog(42, ME);||def my_log(x, base=10) _ @<  >@Math.log(x) / Math.log(base) _ end _ _ my_log(42) _ my_log(42, Math::E)|| ||# variadic-func[#variadic-func-note variadic function]||function firstAndLast() { _ @<  >@if (arguments.length >= 1) { _ @<  >@@<  >@console.log(‘first: ‘ + arguments[0]); _ @<  >@} _ @<  >@if (arguments.length >= 2) { _ @<  >@@<  >@console.log(‘last: ‘ + arguments[1]); _ @<  >@} _ } _ _ ##gray|@@// …@@ operator new in ES6:## _ function firstAndLast(@@…@@a) { _ @<  >@if (a.length >= 1) { _ @<  >@@<  >@console.log(‘first: ‘ + a[0]); _ @<  >@} _ @<  >@if (a.length >= 2) { _ @<  >@@<  >@console.log(‘last: ‘ + a[1]); _ @<  >@} _ }||def firstandlast(a): _ _ @<  >@if len(a) >= 1: _ @<  >@@<  >@print(‘first: ‘ + str(a[0])) _ _ @<  >@if len(a) >= 2: _ @<  >@@<  >@print(‘last: ‘ + str(a[-1]))||function firstandlast() _ { _ _ @<  >@$argcnt = funcnum_args(); _ _ @<  >@if ($arg_cnt >= 1) { _ @<  >@@<  >@$n = funcgetarg(0); _ @<  >@@<  >@echo “first: “ . $n . “\n”; _ @<  >@} _ _ @<  >@if ($arg_cnt >= 2) { _ @<  >@@<  >@$a = funcgetargs(); _ @<  >@@<  >@$n = $a[$arg_cnt-1]; _ @<  >@@<  >@echo “last: “ . $n . “\n”; _ @<  >@} _ }||def firstandlast(a) _ _ @<  >@if a.size >= 1 _ @<  >@@<  >@puts “first: #{a[0]}” _ @<  >@end _ _ @<  >@if a.size >= 2 _ @<  >@@<  >@puts “last: #{a[-1]}” _ @<  >@end _ end|| ||# apply-func[#apply-func-note pass array elements as separate arguments]||let a = [1, 2, 3]; _ _ let sum = add3(@@…@@a);||a = [2, 3] _ _ add3(1, *a) _ _ ##gray|# splat operator can only be used once _

and must appear after other _

unnamed arguments##||$a = [1, 2, 3]; _

_ calluserfunc_array(“add3”, $a);||a = [2, 3] _ _ add3(1, *a) _ _ ##gray|# splat operator can be used multiple _

times and can appear before regular _

arguments##||

||# param-alias[#param-alias-note parameter alias]||##gray|//none//##||##gray|//none//##||function firstandsecond(&$a) _ { _ @<  >@return [$a[0], $a[1]]; _ }||##gray|//none//##|| ||# named-param[#named-param-note named parameters] _ @< >@||##gray|//none//##||def fequal(x, y, eps=0.01): _ @<  >@return abs(x - y) < eps _ _ fequal(1.0, 1.001) _ fequal(1.0, 1.001, eps=0.1@@@@10)||##gray|//none//##||def fequals(x, y, eps: 0.01) _ @<  >@(x - y).abs < eps _ end _ _ fequals(1.0, 1.001) _ fequals(1.0, 1.001, eps: 0.110)|| ||# retval[#retval-note return value] _ @< >@||##gray|return //arg or// undefined.## _ _ ##gray|//If invoked with// new //and// return //value not an object, returns// this.##||##gray|return //arg or// None##||##gray|return //arg or// NULL##||##gray|return //arg or last expression evaluated##//|| ||# multiple-retval[#multiple-retval-note multiple return values] _ @< >@||function firstAndSecond(a) { _ @<  >@return [a[0], a[1]]; _ } _ _ let [x, y] = firstAndSecond([6, 7, 8]); _ ||def firstandsecond(a): _ @<  >@return a[0], a[1] _ _ x, y = firstandsecond([6, 7, 8])||function firstandsecond(&$a) _ { _ @<  >@return [$a[0], $a[1]]; _ } _ _ $a = [6, 7, 8]; _ list($x, $y) = _ @<  >@firstandsecond($a);||def firstandsecond(a) _ @<  >@return a[0], a[1] _ end _ _ x, y = firstandsecond([6, 7, 8])|| ||# anonymous-func-literal[#anonymous-func-literal-note anonymous function literal] _ @< >@||let square = function (x) { _ @<  >@return x * x; _ }; _ _ ##gray|@@//@@ => new in ES6:## _ let square = (x) => { return x * x; }; _ _ ##gray|@@//@@ expression body variant:## _ let square = (x) => x * x;||##gray|# body must be an expression:## _ square = lambda x: x * x||$square = function ($x) { _ @<  >@return $x * $x; _ };||square = lambda { |x| x * x }|| ||# invoke-anonymous-func[#invoke-anonymous-func-note invoke anonymous function]||square(2) _ _ ((x) => (x * x)(2)||square(2) _ _ (lambda x: x * x)(2)||$square(2)||square.call(2) _ _ ##gray|# alternative syntax:## _ square[2]|| ||# func-as-val[#func-as-val-note function as value] _ @< >@||let func = add3;||func = add3||$func = “add3”;||func = lambda { |args| add3(args) }|| ||# private-state-func[#private-state-func-note function with private state]||function counter() { _ @<  >@counter.i += 1; _ @<  >@return counter.i; _ } _ _ counter.i = 0; _ console.log(counter());||##gray|# state not private:## _ def counter(): _ @<  >@counter.i += 1 _ @<  >@return counter.i _ _ counter.i = 0 _ print(counter())||function counter() _ { _ @<  >@static $i = 0; _ @<  >@return ++$i; _ } _ _ echo counter();||##gray|//none//##|| ||# closure[#closure-note closure]||function makeCounter () { _ @<  >@let i = 0; _ _ @<  >@return function () { _ @<  >@@<  >@i += 1; _ @<  >@@<  >@return i; _ @<  >@}; _ } _ _ let nays = makeCounter(); _ console.log(nays());||def make_counter(): _ @<  >@i = 0 _ @<  >@def counter(): _ @<  >@@<  >@##gray|# new in Python 3:## _ @<  >@@<  >@nonlocal i _ @<  >@@<  >@i += 1 _ @<  >@@<  >@return i _ @<  >@return counter _ _ nays = make_counter() _ print(nays())||function make_counter() _ { _ @<  >@$i = 0; _ @<  >@return function () use (&$i) { _ @<  >@@<  >@return ++$i; _ @<  >@}; _ } _ _ $nays = make_counter(); _ echo $nays();||def make_counter _ @<  >@i = 0 _ @<  >@return lambda { i +=1; i } _ end _ _ nays = make_counter _ puts nays.call|| ||# generator[#generator-note generator]||function * makeCounter () { _ @<  >@let i = 0; _ @<  >@while (true) { _ @<  >@@<  >@yield ++i; _ @<  >@} _ } _ _ let nays = makeCounter(); _ for (let cnt of nays) { _ @<  >@console.log(cnt); _ @<  >@if (cnt > 100) { _ @<  >@@<  >@break; _ @<  >@} _ }||##gray|# cf. itertools library## _ _ def make_counter(): _ @<  >@i = 0 _ @<  >@while True: _ @<  >@@<  >@i += 1 _ @<  >@@<  >@yield i _ _ nays = make_counter() _ ##gray|# Python 2: nays.next()## _ print(next(nays)) _ _ for cnt in nays: _ @<  >@print(cnt) _ @<  >@if cnt > 100: _ @<  >@@<  >@break _ _ ##gray|# Returning without yielding raises _

StopIteration exception.##||##gray|# PHP 5.5:## _

function make_counter() { _ @<  >@$i = 0; _ @<  >@while (1) { _ @<  >@@<  >@yield ++$i; _ @<  >@} _ } _ _ $nays = make_counter(); _ ##gray|# does not return a value:## _ $nays->next(); _ ##gray|# runs generator if generator has not _

yet yielded:## _

echo $nays->current();||def make_counter _ @<  >@return Fiber.new do _ @<  >@@<  >@i = 0 _ @<  >@@<  >@while true _ @<  >@@<  >@@<  >@i += 1 _ @<  >@@<  >@@<  >@Fiber.yield i _ @<  >@@<  >@end _ @<  >@end _ end _ _ nays = make_counter _ puts nays.resume|| ||# decorator[#decorator-note decorator]||##gray|//none//##||def logcall(f): _ @<  >@def wrapper(*a, *opts): _ @<  >@@<  >@print(‘calling ‘ + f.@@name@@) _ @<  >@@<  >@f(a, **opts) _ @<  >@@<  >@print(‘called ‘ + f.@@name@@) _ @<  >@return wrapper _ _ @logcall _ def square(x): _ @<  >@return x * x|| || || ||# invoke-op-like-func[#invoke-op-like-func-note invoke operator like function]||##gray|//none//##||import operator _ _ operator.mul(3, 7) _ _ a = [‘foo’, ‘bar’, ‘baz’] _ operator.itemgetter(2)(a)|| ||3.(7) _ _ a = [‘foo’, ‘bar’, ‘baz’] _ a.|| ||||||||||~ # execution-control[#execution-control-note execution control]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# if[#if-note if] _ @< >@||if (n === 0) { _ @<  >@console.log(‘no hits’); _ } else if (n === 1) { _ @<  >@console.log(‘1 hit’); _ } else { _ @<  >@console.log(n + ‘ hits’); _ }||if 0 == n: _ @<  >@print(‘no hits’) _ elif 1 == n: _ @<  >@print(‘one hit’) _ else: _ @<  >@print(str(n) + ‘ hits’)||if ( 0 == $n ) { _ @<  >@echo “no hits\n”; _ } elseif ( 1 == $n ) { _ @<  >@echo “one hit\n”; _ } else { _ @<  >@echo “$n hits\n”; _ }||if n == 0 _ @<  >@puts “no hits” _ elsif 1 == n _ @<  >@puts “one hit” _ else _ @<  >@puts “#{n} hits” _ end|| ||# switch[#switch-note switch]||switch (n) { _ case 0: _ @<  >@console.log(‘no hits\n;); _ @<  >@break; _ case 1: _ @<  >@console.log(‘one hit\n’); _ @<  >@break; _ default: _ @<  >@console.log(n + ‘ hits\n’); _ }||##gray|//none//##||switch ($n) { _ case 0: _ @<  >@echo “no hits\n”; _ @<  >@break; _ case 1: _ @<  >@echo “one hit\n”; _ @<  >@break; _ default: _ @<  >@echo “$n hits\n”; _ }||case n _ when 0 _ @<  >@puts “no hits” _ when 1 _ @<  >@puts “one hit” _ else _ @<  >@puts “#{n} hits” _ end|| ||# while[#while-note while] _ @< >@||while (i < 100) { _ @<  >@i += 1; _ }||while i < 100: _ @<  >@i += 1|| while ( $i < 100 ) { $i++; }||while i < 100 do _ @<  >@i += 1 _ end|| ||# for[#for-note for] _ @< >@||for (let i = 0; i < 10; ++i) { _ @<  >@console.log(i); _ }||for i in range(1, 11): _ @<  >@print(i)||for ($i = 1; $i <= 10; $i++) { _ @<  >@echo “$i\n”; _ }||##gray|//none//##|| ||# break[#break-note break] _ @< >@||for (let i = 30; i < 50; ++i) { _ @<  >@if (i % 7 === 0) { _ @<  >@@<  >@console.log(‘first multiple: ‘ + i); _ @<  >@@<  >@break; _ @<  >@} _ }||break||break||break|| ||# continue[#continue-note continue] _ @< >@||for (let i = 30; i < 50; ++i) { _ @<  >@if (i % 7 === 0) { _ @<  >@@<  >@continue; _ @<  >@} _ @<  >@console.log(‘not divisible: ‘ + i); _ }||continue||continue||next|| ||# statement-modifiers[#statement-modifiers-note statement modifiers] _ @< >@||##gray|//none//##||##gray|//none//##||##gray|//none//##||puts “positive” if i > 0 _ puts “nonzero” unless i == 0|| ||||||||||~ # exceptions[#exceptions-note exceptions]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# base-exc[#base-exc-note base exception]||##gray|//Any value can be thrown.//##||BaseException _ _ ##gray|//User-defined exceptions should subclass// Exception.## _ _ ##gray|//In Python 2 old-style classes can be thrown.//##||Exception||Exception _ _ ##gray|//User-defined exceptions should subclass// StandardError.##|| ||# predefined-exc[#predefined-exc-note predefined exceptions]||Error _ @<  >@EvalError _ @<  >@RangeError _ @<  >@ReferenceError _ @<  >@SyntaxError _ @<  >@TypeError _ @<  >@URIError||BaseException _ @<  >@Exception _ @<  >@@<  >@TypeError _ @<  >@@<  >@ImportError _ @<  >@@<  >@AssertionError _ @<  >@@<  >@ArithmeticError _ @<  >@@<  >@@<  >@FloatingPointError _ @<  >@@<  >@@<  >@OverflowError _ @<  >@@<  >@@<  >@ZeroDivisionError _ @<  >@@<  >@SyntaxError _ @<  >@@<  >@OSError _ @<  >@@<  >@MemoryError _ @<  >@@<  >@StopIteration _ @<  >@@<  >@Error _ @<  >@@<  >@SystemError _ @<  >@@<  >@ValueError _ @<  >@@<  >@@<  >@UnicodeError _ @<  >@@<  >@@<  >@@<  >@UnicodeEncodeError _ @<  >@@<  >@@<  >@@<  >@UnicodeDecodeError _ @<  >@@<  >@@<  >@@<  >@UnicodeTranslateError _ @<  >@@<  >@@<  >@UnsupportedOperation _ @<  >@@<  >@NameError _ @<  >@@<  >@AttributeError _ @<  >@@<  >@RuntimeError _ @<  >@@<  >@LookupError _ @<  >@@<  >@@<  >@IndexError _ @<  >@@<  >@@<  >@KeyError _ @<  >@@<  >@EOFError _ @<  >@GeneratorExit _ @<  >@KeyboardInterrupt _ @<  >@SystemExit||Exception _ @<  >@LogicException _ @<  >@@<  >@BadFunctionCallException _ @<  >@@<  >@@<  >@BadMethodCallException _ @<  >@@<  >@DomainException _ @<  >@@<  >@InvalidArgumentException _ @<  >@@<  >@LengthException _ @<  >@@<  >@OutOfRangeException _ @<  >@RuntimeException _ @<  >@@<  >@OutOfBoundsException _ @<  >@@<  >@OverflowException _ @<  >@@<  >@RangeException _ @<  >@@<  >@UnderflowException _ @<  >@@<  >@UnexpectedValueException||Exception _ @<  >@NoMemoryError _ @<  >@ScriptError _ @<  >@@<  >@LoadError _ @<  >@@<  >@NotImplementedError _ @<  >@@<  >@SyntaxError _ @<  >@SignalException _ @<  >@StandardError _ @<  >@@<  >@ArgumentError _ @<  >@@<  >@IOError _ @<  >@@<  >@@<  >@EOFError _ @<  >@@<  >@IndexError _ @<  >@@<  >@LocalJumpError _ @<  >@@<  >@NameError _ @<  >@@<  >@RangeError _ @<  >@@<  >@RegexpError _ @<  >@@<  >@RuntimeError _ @<  >@@<  >@SecurityError _ @<  >@@<  >@SocketError _ @<  >@@<  >@SystemCallError _ @<  >@@<  >@@<  >@Errno:: _ @<  >@@<  >@SystemStackError _ @<  >@@<  >@ThreadError _ @<  >@@<  >@TypeError _ @<  >@@<  >@ZeroDivisionError _ @<  >@SystemExit _ @<  >@fatal|| ||# raise-exc[#raise-exc-note raise exception] _ @< >@||throw new Error(“bad arg”);||raise Exception(‘bad arg’)||throw new Exception(“bad arg”);||##gray|# raises RuntimeError## _ raise “bad arg”|| ||# catch-all-handler[#catch-all-handler-note catch-all handler] _ @< >@||try { _ @<  >@risky(); _ } catch (e) { _ @<  >@console.log( _ @<  >@@<  >@’risky failed: ‘ + e.message); _ }||try: _ @<  >@risky() _ except: _ @<  >@print(‘risky failed’)||try { _ @<  >@risky(); _ } catch (Exception $e) { _ @<  >@echo “risky failed: “, _ @<  >@@<  >@$e->getMessage(), “\n”; _ }||##gray|# catches StandardError## _ begin _ @<  >@risky _ rescue _ @<  >@print “risky failed: “ _ @<  >@puts $!.message _ end|| ||# re-raise-exc[#re-raise-exc-note re-raise exception]||try { _ @<  >@throw new Error(“bam!”); _ } catch (e) { _ @<  >@console.log(‘re-raising@@…@@’); _ @<  >@throw e; _ }||try: _ @<  >@raise Exception(‘bam!’) _ except: _ @<  >@print(‘re-raising@@…@@’) _ @<  >@raise|| ||begin _ @<  >@raise “bam!” _ rescue _ @<  >@puts “re-raising…” _ @<  >@raise _ end _ _ ##gray|# if rescue clause raises different exception, _

original exception preserved at e.cause##||

||# last-exc-global[#last-exc-global-note global variable for last exception]||##gray|//none//##||##gray|//last exception:// sys.exc_info()[1]##||##gray|//none//##||##gray|//last exception:// $!## _ ##gray|//backtrace array of exc.:// $@## _ ##gray|//exit status of child:// $?##|| ||# def-exc[#def-exc-note define exception]||function Bam(msg) { _ @<  >@this.message = msg; _ } _ _ Bam.prototype = new Error;||class Bam(Exception): _ @<  >@def @@init@@(self): _ @<  >@@<  >@super(Bam, self).@@init@@(‘bam!’)||class Bam extends Exception _ { _ @<  >@function @@@@construct() _ @<  >@{ _ @<  >@@<  >@parent::@@@@construct(“bam!”); _ @<  >@} _ }||class Bam < Exception _ @<  >@def initialize _ @<  >@@<  >@super(“bam!”) _ @<  >@end _ end|| ||# handle-exc[#handle-exc-note handle exception]||try { _ @<  >@throw new Bam(“bam!”); _ } catch (e) { _ @<  >@if (e instanceof Bam) { _ @<  >@@<  >@console.log(e.message); _ @<  >@} _ @<  >@else { _ @<  >@@<  >@throw e; _ @<  >@} _ }||try: _ @<  >@raise Bam() _ except Bam as e: _ @<  >@print(e)||try { _ @<  >@throw new Bam; _ } catch (Bam $e) { _ @<  >@echo $e->getMessage(), “\n”; _ }||begin _ @<  >@raise Bam.new _ rescue Bam => e _ @<  >@puts e.message _ end|| ||# finally-block[#finally-block-note finally block] _ @< >@||acquireResource(); _ try { _ @<  >@risky(); _ } finally { _ @<  >@releaseResource(); _ }||acquire_resource() _ try: _ @<  >@risky() _ finally: _ @<  >@release_resource()||##gray|//PHP 5.5://## _ acquire_resource(); _ try { _ @<  >@risky(); _ } _ finally { _ @<  >@release_resource(); _ }||acquire_resource _ begin _ @<  >@risky _ ensure _ @<  >@release_resource _ end|| ||||||||||~ # threads[#threads-note threads]|| ||~ ||~ node.js||~ python||~ php||~ ruby|| ||# start-thread[#start-thread-note start thread] _ @< >@|| ||class sleep10(threading.Thread): _ @<  >@def run(self): _ @<  >@@<  >@time.sleep(10) _ _ thr = sleep10() _ thr.start()|| || thr = Thread.new { sleep 10 }|| ||# wait-on-thread[#wait-on-thread-note wait on thread] _ @< >@|| ||thr.join()|| ||thr.join|| ||# sleep[#sleep-note sleep]|| ||import time _ _ time.sleep(0.5)||##gray|# a float argument will be truncated _

to an integer:## _

sleep(1);||sleep(0.5)|| ||# timeout[#timeout-note timeout]|| ||import signal, time _ _ class Timeout(Exception): pass _ _ def timeout_handler(signo, fm): _ @<  >@raise Timeout() _ _ signal.signal(signal.SIGALRM, _ @<  >@timeout_handler) _ _ try: _ @<  >@signal.alarm(5) _ @<  >@mighttaketoo_long() _ except Timeout: _ @<  >@pass _ signal.alarm(0)||##gray|//use// settimelimit //to limit execution time of the entire script; use// streamsettimeout //to limit time spent reading from a stream opened with// fopen //or// fsockopen##||require ‘timeout’ _ _ begin _ @<  >@Timeout.timeout(5) do _ @<  >@@<  >@mighttaketoo_long _ @<  >@end _ rescue Timeout::Error _ end|| ||~ ||~ ##efefef|@@__________________________________________________@@##||~ ##efefef|@@_______________________________________________@@##||~ ##efefef|@@_______________________________________________@@##||~ ##efefef|@@__________________________________________________@@##||

sheet two]: streams] | asynchronous events] | files] | directories] | processes and environment] | option parsing] | libraries and namespaces] | objects] | inheritance and polymorphism] | reflection] | net and web] | gui] | databases] | unit tests] | logging] | debugging]

# version-note + [#version Version]

# version-used-note ++ [#version-used version used]

The versions used for testing code in the reference sheet.

# version-note ++ [#version show version]

How to get the version.

php:

The function {{phpversion()}} will return the version number as a string.

python:

The following function will return the version number as a string:

code import platform

platform.python_version() /code

ruby:

Also available in the global constant {{RUBY_VERSION}}.

# implicit-prologue-note ++ [#implicit-prologue implicit prologue]

Code which examples in the sheet assume to have already been executed.

javascript:

{{underscore.js}} adds some convenience functions as attributes of an object which is normally stored in the underscore {{_}} variable. E.g.:

code _.map([1, 2, 3], function(n){ return n * n; }); /code

[http://cdnjs.com/libraries/underscore.js cdnjs] hosts underscore.js and other JavaScript libraries for situations where it is inconvenient to have the webserver host the libraries.

When using {{underscore.js}} with the Node REPL, there is a conflict, since the Node REPL uses the underscore {{_}} variable to store the result of the last evaluation.

code $ npm install underscore

$ node

var us = require(‘underscore’); _

us.keys({"one”: 1, “two”: 2}); [ ‘one’, ‘two’ ]

/code

php:

The {{mbstring}} package adds UTF-8 aware string functions with {{mb_}} prefixes.

python:

We assume that {{os}}, {{re}}, and {{sys}} are always imported.

# grammar-execution-note + [#grammar-execution Grammar and Execution]

# interpreter-note ++ [#interpreter interpreter]

The customary name of the interpreter and how to invoke it.

php:

{{php -f}} will only execute portions of the source file within a <?php ##gray|//php code//## ?> tag as php code. Portions of the source file outside of such tags is not treated as executable code and is echoed to standard out.

If short tags are enabled, then php code can also be placed inside <? ##gray|//php code//## ?> and <?= ##gray|//php code//## ?> tags.

<?= ##gray|//php code//## ?> is identical to <?php echo ##gray|//php code//## ?>.

# repl-note ++ [#repl repl]

The customary name of the repl.

php:

The {{php -a}} REPL does not save or display the result of an expression.

python:

The python repl saves the result of the last statement in @@_@@.

ruby:

{{irb}} saves the result of the last statement in @@_@@.

# cmd-line-program-note ++ [#cmd-line-program command line program]

How to pass the code to be executed to the interpreter as a command line argument.

# block-delimiters-note ++ [#block-delimiters block delimiters]

How blocks are delimited.

python:

Python blocks begin with a line that ends in a colon. The block ends with the first line that is not indented further than the initial line. Python raises an IndentationError if the statements in the block that are not in a nested block are not all indented the same. Using tabs in Python source code is unrecommended and many editors replace them automatically with spaces. If the Python interpreter encounters a tab, it is treated as 8 spaces.

The python repl switches from a {{@@>>>@@}} prompt to a … prompt inside a block. A blank line terminates the block.

Colons are also used to separate keys from values in dictionary literals and in sequence slice notation.

ruby:

Curly brackets {} delimit blocks. A matched curly bracket pair can be replaced by the {{do}} and {{end}} keywords. By convention curly brackets are used for one line blocks.

The {{end}} keyword also terminates blocks started by {{def}}, {{class}}, or {{module}}.

Curly brackets are also used for hash literals, and the #{ } notation is used to interpolate expressions into strings.

# statement-separator-note ++ [#statement-separator statement separator]

How the parser determines the end of a statement.

php:

Inside braces statements must be terminated by a semicolon. The following causes a parse error:

code <? if (true) { echo “true” } ?> /code

The last statement inside {{<?= ?>}} or {{<? ?>}} tags does not need to be semicolon terminated, however. The following code is legal:

code <?= $a = 1 ?> <? echo $a ?> /code

python:

Newline does not terminate a statement when:

Python single quote ‘‘ and double quote ““ strings cannot contain newlines except as the two character escaped form \n. Putting a newline in these strings results in a syntax error. There is however a multi-line string literal which starts and ends with three single quotes ‘‘‘ or three double quotes: “““.

A newline that would normally terminate a statement can be escaped with a backslash.

ruby:

Newline does not terminate a statement when:

Ruby permits newlines in array [] or hash literals, but only after a comma , or associator =>. Putting a newline before the comma or associator results in a syntax error.

A newline that would normally terminate a statement can be escaped with a backslash.

# source-code-encoding-note ++ [#source-code-encoding source code encoding]

How to identify the character encoding for a source code file.

Setting the source code encoding makes it possible to safely use non-ASCII characters in string literals and regular expression literals.

# eol-comment-note ++ [#eol-comment end-of-line comment]

How to create a comment that ends at the next newline.

# multiple-line-comment-note ++ [#multiple-line-comment multiple line comment]

How to comment out multiple lines.

python:

The triple single quote ‘‘‘ and triple double quote “““ syntax is a syntax for string literals.

# var-expr-note + [#var-expr Variables and Expressions]

# local-var-note ++ [#local-var local variable]

How to declare variables which are local to the scope defining region which immediately contain them.

php:

Variables do not need to be declared and there is no syntax for declaring a local variable. If a variable with no previous reference is accessed, its value is //NULL//.

python:

A variable is created by assignment if one does not already exist. If the variable is inside a function or method, then its scope is the body of the function or method. Otherwise it is a global.

ruby:

Variables are created by assignment. If the variable does not have a dollar sign ($) or ampersand (@) as its first character then its scope is scope defining region which most immediately contains it.

A lower case name can refer to a local variable or method. If both are defined, the local variable takes precedence. To invoke the method make the receiver explicit: e.g. self.//name//. However, outside of class and modules local variables hide functions because functions are private methods in the class //Object//. Assignment to //name// will create a local variable if one with that name does not exist, even if there is a method //name//.

# file-scope-var-note ++ [#file-scope-var file scope variable]

How to define a variable with scope bound by the source file.

# global-var-note ++ [#global-var global variable]

How to declare and access a variable with global scope.

php:

A variable is global if it is used at the top level (i.e. outside any function definition) or if it is declared inside a function with the //global// keyword. A function must use the //global// keyword to access the global variable.

python:

A variable is global if it is defined at the top level of a file (i.e. outside any function definition). Although the variable is global, it must be imported individually or be prefixed with the module name prefix to be accessed from another file. To be accessed from inside a function or method it must be declared with the //global// keyword.

ruby:

A variable is global if it starts with a dollar sign: $.

# const-note ++ [#const constant]

How to declare a constant.

php:

A constant can be declared inside a class:

code class Math { const pi = 3.14; } /code

Refer to a class constant like this:

code Math::pi /code

ruby:

Capitalized variables contain constants and class/module names. By convention, constants are all caps and class/module names are camel case. The ruby interpreter does not prevent modification of constants, it only gives a warning. Capitalized variables are globally visible, but a full or relative namespace name must be used to reach them: e.g. Math::PI.

# assignment-note ++ [#assignment assignment]

How to assign a value to a variable.

python:

If the variable on the left has not previously been defined in the current scope, then it is created. This may hide a variable in a containing scope.

Assignment does not return a value and cannot be used in an expression. Thus, assignment cannot be used in a conditional test, removing the possibility of using assignment (=) when an equality test (==) was intended. Assignments can nevertheless be chained to assign a value to multiple variables:

code a = b = 3 /code

ruby:

Assignment operators have right precedence and evaluate to the right argument, so they can be chained. If the variable on the left does not exist, then it is created.

# parallel-assignment-note ++ [#parallel-assignment parallel assignment]

How to assign values to variables in parallel.

python:

The r-value can be a list or tuple:

code nums = [1, 2, 3] a, b, c = nums morenums = (6, 7, 8) d, e, f = morenums /code

Nested sequences of expression can be assigned to a nested sequences of l-values, provided the nesting matches. This assignment will set a to 1, b to 2, and c to 3:

code (a,[b,c]) = [1,(2,3)] /code

This assignment will raise a {{TypeError}}:

code (a,(b,c)) = ((1,2),3) /code

In Python 3 the splat operator {{*}} can be used to collect the remaining right side elements in a list:

code x, y, *z = 1, 2 # assigns [] to z x, y, *z = 1, 2, 3 # assigns [3] to z x, y, *z = 1, 2, 3, 4 # assigns [3, 4] to z /code

ruby:

The r-value can be an array:

code nums = [1, 2, 3] a,b,c = nums /code

# swap-note ++ [#swap swap]

How to swap the values held by two variables.

# compound-assignment-note ++ [#compound-assignment compound assignment]

Compound assignment operators mutate a variable, setting it to the value of an operation which takes the previous value of the variable as an argument.

If {{}} is a binary operator and the language has the compound assignment operator {{=}}, then the following are equivalent:

code x = y x = x y /code

The compound assignment operators are displayed in this order:

//First row:// arithmetic operator assignment: addition, subtraction, multiplication, (float) division, integer division, modulus, and exponentiation. //Second row:// string concatenation assignment and string replication assignment //Third row:// logical operator assignment: and, or, xor //Fourth row:// bit operator assignment: left shift, right shift, and, or, xor.

python:

Python compound assignment operators do not return a value and hence cannot be used in expressions.

# incr-decr-note ++ [#incr-decr increment and decrement]

The C-style increment and decrement operators can be used to increment or decrement values. They return values and thus can be used in expressions. The prefix versions return the value in the variable after mutation, and the postfix version return the value before mutation.

Incrementing a value two or more times in an expression makes the order of evaluation significant:

code x = 1; foo(++x, ++x); // foo(2, 3) or foo(3, 2)?

x = 1; y = ++x/++x; // y = 2/3 or y = 3/2? /code

Python avoids the problem by not having an in-expression increment or decrement.

Ruby mostly avoids the problem by providing a non-mutating increment and decrement. However, here is a Ruby expression which is dependent on order of evaluation:

code x = 1 y = (x += 1)/(x += 1) /code

php:

The increment and decrement operators also work on strings. There are postfix versions of these operators which evaluate to the value before mutation:

code $x = 1; $x++; $x–; /code

ruby:

The Integer class defines {{succ}}, {{pred}}, and {{next}}, which is a synonym for {{succ}}.

The String class defines {{succ}}, {{succ!}}, {{next}}, and {{next!}}. {{succ!}} and {{next!}} mutate the string.

# null-note ++ [#null null]

The null literal.

# null-test-note ++ [#null-test null test]

How to test if a variable contains null.

php:

//$v == NULL// does not imply that //$v// is //NULL//, since any comparison between //NULL// and a falsehood will return true. In particular, the following comparisons are true:

code $v = NULL; if ($v == NULL) { echo “true”; }

$v = 0; if ($v == NULL) { echo “sadly true”; }

$v = ‘‘; if ($v == NULL) { echo “sadly true”; } /code

# undef-var-note ++ [#undef-var undefined variable]

The result of attempting to access an undefined variable.

python:

Because a class can implement an {{eq}} method to change the implementation of {{v == None}}, the expression can be {{True}} when {{v}} is not {{None}}.

php:

PHP does not provide the programmer with a mechanism to distinguish an undefined variable from a variable which has been set to NULL.

[https://gist.github.com/1157508 A test] showing that {{isset}} is the logical negation of {{is_null}}.

python:

How to test if a variable is defined:

code notdefined = False try: v except NameError: notdefined = True /code

ruby:

How to test if a variable is defined:

code ! defined?(v) /code

# conditional-expr-note ++ [#conditional-expr conditional expression]

How to write a conditional expression. A ternary operator is an operator which takes three arguments. Since

##gray|//condition//## ? ##gray|//true value//## : ##gray|//false value//##

is the only ternary operator in C, it is unambiguous to refer to it as //the// ternary operator.

python:

The Python conditional expression comes from Algol.

ruby:

The Ruby {{if}} statement is also an expression:

code x = if x > 0 x else -x end /code

# arithmetic-logic-note + [#arithmetic-logic Arithmetic and Logic]

# true-false-note ++ [#true-false true and false]

Literals for the booleans.

These are the return values of the relational operators.

php:

Any identifier which matches TRUE case-insensitive can be used for the TRUE boolean. Similarly for FALSE.

In general, PHP variable names are case-sensitive, but function names are case-insensitive.

When converted to a string for display purposes, TRUE renders as “1” and FALSE as ““. The equality tests {{TRUE == 1}} and {{FALSE == ““}} evaluate as TRUE but the equality tests {{TRUE === 1}} and {{FALSE === ““}} evaluate as FALSE.

# falsehoods-note ++ [#falsehoods falsehoods]

Values which behave like the false boolean in a conditional context.

Examples of conditional contexts are the conditional clause of an {{if}} statement and the test of a {{while}} loop.

python:

Whether a object evaluates to True or False in a boolean context can be customized by implementing a @@nonzero@@ (Python 2) or @@bool@@ (Python 3) instance method for the class.

# logical-op-note ++ [#logical-op logical operators]

Logical and, or, and not.

php, ruby:

&& and @@||@@ have higher precedence than assignment, compound assignment, and the ternary operator (?:), which have higher precedence than //and// and //or//.

# relational-op-note ++ [#relational-op relational operators]

Equality, inequality, greater than, less than, greater than or equal, less than or equal.

php:

Most of the relational operators will convert a string to a number if the other operand is a number. Thus 0 == “0” is true. The operators === and !== do not perform this conversion, so 0 === “0” is false.

python:

Relational operators can be chained. The following expressions evaluate to true:

code 1 < 2 < 3 1 == 1 != 2 /code

In general if //A,,i,,// are expressions and //op,,i,,// are relational operators, then

@<  >@@<  >@{{A,,1,, op,,1,, A,,2,, op,,2,, A,,3,, … A,,n,, op,,n,, A,,n+1,,}}

is true if and only if each of the following is true

@<  >@@<  >@{{A,,1,, op,,1,, A,,2,,}} @<  >@@<  >@{{A,,2,, op,,2,, A,,3,,}} @<  >@@<  >@… @<  >@@<  >@{{A,,n,, op,,n,, A,,n+1,,}}

# min-max-note ++ [#min-max min and max]

How to get the min and max.

# arith-op-note ++ [#arith-op arithmetic operators]

The operators for addition, subtraction, multiplication, float division, integer division, modulus, and exponentiation.

# int-div-note ++ [#int-div integer division]

How to get the integer quotient of two integers.

# divmod-note ++ [#divmod divmod]

How to get the quotient and remainder with single function call.

# int-div-zero-note ++ [#int-div-zero integer division by zero]

What happens when an integer is divided by zero.

# float-div-note ++ [#float-div float division]

How to perform floating point division, even if the operands might be integers.

# float-div-zero-note ++ [#float-div-zero float division by zero]

What happens when a float is divided by zero.

# power-note ++ [#power power]

How to get the value of a number raised to a power.

# sqrt-note ++ [#sqrt sqrt]

The square root function.

# sqrt-negative-one-note ++ [#sqrt-negative-one sqrt -1]

The result of taking the square root of negative one.

# transcendental-func-note ++ [#transcendental-func transcendental functions]

Some mathematical functions. Trigonometric functions are in radians unless otherwise noted. Logarithms are natural unless otherwise noted.

python:

Python also has //math.log10//. To compute the log of //x// for base //b//, use:

code math.log(x)/math.log(b) /code

ruby:

Ruby also has //Math.log2//, //Math.log10//. To compute the log of //x// for base //b//, use

code Math.log(x)/Math.log(b) /code

# transcendental-const-note ++ [#transcendental-const transcendental constants]

Constants for π and Euler’s constant.

# float-truncation-note ++ [#float-truncation float truncation]

How to truncate a float to the nearest integer towards zero; how to round a float to the nearest integer; how to find the nearest integer above a float; how to find the nearest integer below a float; how to take the absolute value.

# abs-val-note ++ [#abs-val absolute value]

How to get the absolute value of a number.

# int-overflow-note ++ [#int-overflow integer overflow]

What happens when the largest representable integer is exceeded.

# float-overflow-note ++ [#float-overflow float overflow]

What happens when the largest representable float is exceeded.

# rational-note ++ [#rational rational numbers]

How to create rational numbers and get the numerator and denominator.

ruby:

Require the library //mathn// and integer division will yield rationals instead of truncated integers.

# complex-note ++ [#complex complex numbers]

python:

Most of the functions in //math// have analogues in //cmath// which will work correctly on complex numbers.

# random-note ++ [#random random integer, uniform float, normal float]

How to generate a random integer between 0 and 99, include, float between zero and one in a uniform distribution, or a float in a normal distribution with mean zero and standard deviation one.

# random-seed-note ++ [#random-seed set random seed, get and restore seed]

How to set the random seed; how to get the current random seed and later restore it.

All the languages in the sheet set the seed automatically to a value that is difficult to predict. The Ruby MRI interpreter uses the current time and process ID, for example. As a result there is usually no need to set the seed.

Setting the seed to a hardcoded value yields a random but repeatable sequence of numbers. This can be used to ensure that unit tests which cover code using random numbers doesn’t intermittently fail.

The seed is global state. If multiple functions are generating random numbers then saving and restoring the seed may be necessary to produce a repeatable sequence.

# bit-op-note ++ [#bit-op bit operators]

The bit operators for left shift, right shift, and, inclusive or, exclusive or, and negation.

# binary-octal-hex-literals-note ++ [#binary-octal-hex-literals binary, octal, and hex literals]

Binary, octal, and hex integer literals

# radix-note ++ [#radix radix]

How to convert integers to strings of digits of a given base. How to convert such strings into integers.

python

Python has the functions {{bin}}, {{oct}}, and {{hex}} which take an integer and return a string encoding the integer in base 2, 8, and 16.

code bin(42) oct(42) hex(42) /code

# strings-note + [#strings Strings]

# str-type-note ++ [#str-type string type]

The type for a string of Unicode characters.

php:

PHP assumes all strings have single byte characters.

python:

In Python 2.7 the {{str}} type assumes single byte characters. A separate {{unicode}} type is available for working with Unicode strings.

In Python 3 the {{str}} type supports multibtye characters and the {{unicode}} type has been removed.

There is a mutable {{bytearray}} type and an immutable {{bytes}} type for working with sequences of bytes.

ruby:

The {{String}} type supports multibtye characters. All strings have an explicit {{Encoding}}.

# str-literal-note ++ [#str-literal string literal]

The syntax for string literals.

python:

String literals may have a {{u}} prefix

code u’lorem ipsum’ u"lorem ipsum” u’’’lorem ipsum’’’ u””"lorem ipsum””” /code

In Python 3, these are identical to literals without the {{u}} prefix.

In Python 2, these create {{unicode}} strings instead of {{str}} strings. Since the Python 2 {{unicode}} type corresponds to the Python 3 {{str}} type, portable code will use the {{u}} prefix.

ruby:

How to specify custom delimiters for single and double quoted strings. These can be used to avoid backslash escaping. If the left delimiter is (, [, or { the right delimiter must be ), ], or }, respectively.

code s1 = %q(lorem ipsum) s2 = %Q(#{s1} dolor sit amet) /code

# newline-in-str-literal-note ++ [#newline-in-str-literal newline in literal]

Whether newlines are permitted in string literals.

python:

Newlines are not permitted in single quote and double quote string literals. A string can continue onto the following line if the last character on the line is a backslash. In this case, neither the backslash nor the newline are taken to be part of the string.

Triple quote literals, which are string literals terminated by three single quotes or three double quotes, can contain newlines:

code ‘‘‘This is two lines’’’

“““This is also two lines””” /code

# str-literal-esc-note ++ [#str-literal-esc literal escapes]

Backslash escape sequences for inserting special characters into string literals.

||||||~ unrecognized backslash escape sequence|| ||~ ||~ double quote||~ single quote|| ||JavaScript|| || || ||PHP||preserve backslash||preserve backslash|| ||Python||preserve backslash||preserve backslash|| ||Ruby||drop backslash||preserve backslash||

python:

When string literals have an {{r}} or {{R}} prefix there are no backslash escape sequences and any backslashes thus appear in the created string. The delimiter can be inserted into a string if it is preceded by a backslash, but the backslash is also inserted. It is thus not possible to create a string with an {{r}} or {{R}} prefix that ends in a backslash. The {{r}} and {{R}} prefixes can be used with single or double quotes:

code r’C:\Documents and Settings\Admin’ r"C:\Windows\System32” /code

The \u##gray|//hhhh//## escapes are also available inside Python 2 Unicode literals. Unicode literals have a //u// prefiix:

code u’lambda: \u03bb’ /code

This syntax is also available in Python 3.3, but not Python 3.2. In Python 3.3 it creates a string of type {{str}} which has the same features as the {{unicode}} type of Python 2.7.

# here-doc-note ++ [#here-doc here document]

Here documents are strings terminated by a custom identifier. They perform variable substitution and honor the same backslash escapes as double quoted strings.

python:

Triple quotes honor the same backslash escape sequences as regular quotes, so triple quotes can otherwise be used like here documents:

code s = ‘‘‘here document there computer ‘‘‘ /code

ruby:

Put the customer identifier in single quotes to prevent variable interpolation and backslash escape interpretation:

code s = <<’EOF’ Ruby code uses #{var} type syntax to interpolate variables into strings. EOF /code

# var-interpolation-note ++ [#var-interpolation variable interpolation]

How to interpolate variables into strings.

python:

The f’1 + 1 = {1 + 1}’ and f"1 + 1 = {1 + 1}” literals, which support variable interpolation and expression interpolation, are new in Python 3.6.

{{str.format}} will take named or positional parameters. When used with named parameters {{str.format}} can mimic the variable interpolation feature of the other languages.

A selection of variables in scope can be passed explicitly:

code count = 3 item = ‘ball’ print(‘{count} {item}s’.format( count=count, item=item)) /code

Python 3 has {{format_map}} which accepts a {{dict}} as an argument:

code count = 3 item = ‘ball’ print(‘{count} {item}s’.format_map(locals())) /code

# expr-interpolation-note ++ [#expr-interpolation expression interpolation]

How to interpolate the result of evaluating an expression into a string.

# format-str-note ++ [#format-str format string]

How to create a string using a printf style format.

python:

The % operator will interpolate arguments into printf-style format strings.

The {{str.format}} with positional parameters provides an alternative format using curly braces {0}, {1}, … for replacement fields.

The curly braces are escaped by doubling:

code ‘to insert parameter {0} into a format, use {{{0}}}’.format(3) /code

If the replacement fields appear in sequential order and aren’t repeated, the numbers can be omitted:

code ‘lorem {} {} {}’.format(‘ipsum’, 13, 3.7) /code

# mutable-str-note ++ [#mutable-str are strings mutable?]

Are strings mutable?

# copy-str-note ++ [#copy-str copy string]

How to copy a string such that changes to the original do not modify the copy.

# str-concat-note ++ [#str-concat concatenate]

The string concatenation operator.

# str-replicate-note ++ [#str-replicate replicate]

The string replication operator.

# translate-case-note ++ [#translate-case translate case]

How to put a string into all caps or all lower case letters.

# capitalize-note ++ [#capitalize capitalize]

How to capitalize a string and the words in a string.

The examples lowercase non-initial letters.

php:

How to define a UTF-8 aware version of {{ucfirst}}. This version also puts the rest of the string in lowercase:

code function mbucfirst($string, $encoding = “UTF-8”) { $strlen = mbstrlen($string, $encoding); $firstChar = mbsubstr($string, 0, 1, $encoding); $then = mbsubstr(mbstrtolower($string), 1, $strlen - 1, $encoding); return mbstrtoupper($firstChar, $encoding) . $then; } /code

ruby:

Rails monkey patches the {{String}} class with the {{titleize}} method for capitalizing the words in a string.

# trim-note ++ [#trim trim]

How to remove whitespace from the ends of a string.

# pad-note ++ [#pad pad]

How to pad the edge of a string with spaces so that it is a prescribed length.

# num-to-str-note ++ [#num-to-str number to string]

How to convert numeric data to string data.

# fmt-float-note ++ [#fmt-float format float]

How to control the number of digits in a float when converting it to a string.

python:

The number after the decimal controls the number of digits after the decimal:

code

‘%.2f’ % math.pi ‘3.14’ /code

The number after the decimal controls the total number of digits:

code

‘{:.3}’.format(math.pi) ‘3.14’ /code

# str-to-num-note ++ [#str-to-num string to number]

How to convert string data to numeric data.

php:

PHP converts a scalar to the desired type automatically and does not raise an error if the string contains non-numeric data. If the start of the string is not numeric, the string evaluates to zero in a numeric context.

python:

float and int raise an error if called on a string and any part of the string is not numeric.

ruby:

toi and tof always succeed on a string, returning the numeric value of the digits at the start of the string, or zero if there are no initial digits.

# str-join-note ++ [#str-join string join]

How to concatenate the elements of an array into a string with a separator.

# split-note ++ [#split split]

How to split a string containing a separator into an array of substrings.

See also [#scan scan].

python:

{{str.split()}} takes simple strings as delimiters; use {{re.split()}} to split on a regular expression:

code re.split(‘\s+’, ‘do re mi fa’) re.split(‘\s+’, ‘do re mi fa’, 1) /code

# split-in-two-note ++ [#split-in-two split in two]

How to split a string in two.

javascript:

A regular expression is probably the best method for splitting a string in two:

code var m = /([ ]+) (.+)/.exec(“do re mi”); var first = m[1]; var rest = m[2]; /code

This technique works when the delimiter is a fixed string:

code var a = “do re mi”.split(“ “); var first = a[0]; var rest = a.splice(1).join(“ “); /code

python:

Methods for splitting a string into three parts using the first or last occurrence of a substring:

code ‘do re mi’.partition(‘ ‘) # returns (‘do’, ‘ ‘, ‘re mi’) ‘do re mi’.rpartition(‘ ‘) # returns (‘do re’, ‘ ‘, ‘mi’) /code

# split-keep-delimiters-note ++ [#split-keep-delimiters split and keep delimiters]

How to split a string with the delimiters preserved as separate elements.

# prefix-suffix-test-note ++ [#prefix-suffix-test prefix and suffix test]

How to test whether a string begins or ends with a substring.

# str-len-note ++ [#str-len length]

How to get the length in characters of a string.

# index-substr-note ++ [#index-substr index of substring]

How to find the index of the leftmost occurrence of a substring in a string; how to find the index of the rightmost occurrence.

# extract-substr-note ++ [#extract-substr extract substring]

How to extract a substring from a string by index.

# bytes-type-note ++ [#bytes-type byte array type]

The type for an array of bytes.

# bytes-to-str-note ++ [#bytes-to-str byte array to string]

How to convert an array of bytes to a string of Unicode characters.

# str-to-bytes-note ++ [#str-to-bytes string to byte array]

How to convert a string of Unicode characters to an array of bytes.

# lookup-char-note ++ [#lookup-char character lookup]

How to look up the character in a string at an index.

# chr-ord-note ++ [#chr-ord chr and ord]

Converting characters to ASCII codes and back.

The languages in this reference sheet do not have character literals, so characters are represented by strings of length one.

# str-to-char-array-note ++ [#str-to-char-array to array of characters]

How to split a string into an array of single character strings.

# translate-char-note ++ [#translate-char translate characters]

How to apply a character mapping to a string.

python:

In Python 2, the string of lowercase letters is in {{string.lowercase}} instead of {{string.ascii_lowercase}}.

In Python 2, the {{maketrans}} function is in the module {{string}} instead of {{str}}.

# delete-char-note ++ [#delete-char delete characters]

How to remove all specified characters from a string; how to remove all but the specified characters from a string.

# squeeze-char-note ++ [#squeeze-char squeeze characters]

How to replace multiple adjacent occurrences of a character with a single occurrence.

# regexes-note + [#regexes Regular Expressions]

Regular expressions or regexes are a way of specifying sets of strings. If a string belongs to the set, the string and regex “match”. Regexes can also be used to parse strings.

The modern notation for regexes was introduced by Unix command line tools in the 1970s. POSIX standardized the notation into two types: extended regexes and the more archaic basic regexes. Perl regexes are extended regexes augmented by new character class abbreviations and a few other features introduced by the Perl interpreter in the 1990s. All the languages in this sheet use Perl regexes.

Any string that doesn’t contain regex metacharacters is a regex which matches itself. The regex metacharacters are: {{[ ] . | ( ) * + ? { } ^ $ }}

character classes: [ ] .

A character class is a set of characters in brackets:{{ [ ].}} When used in a regex it matches any character it contains.

Character classes have their own set of metacharacters: {{^ - \ ]}}

The {{^}} is only special when it is the first character in the character class. Such a character class matches its complement; that is, any character not inside the brackets. When not the first character the {{^}} refers to itself.

The hyphen is used to specify character ranges: e.g. {{0-9}} or {{A-Z}}. When the hyphen is first or last inside the brackets it matches itself.

The backslash can be used to escape the above characters or the terminal character class delimiter: {{]}}. It can be used in character class abbreviations or string backslash escapes.

The period {{.}} is a character class abbreviation which matches any character except for newline. In all languages the period can be made to match all characters. PHP uses the {{m}} modifier. Python uses the {{re.M}} flag. Ruby uses the {{s}} modifier.

# regex-char-class-abbrev character class abbreviations:

||~ abbrev||~ name||~ character class|| ||\d||digit||[0-9]|| ||\D||nondigit||[^0-9]|| ||\h||##gray|//PHP://## horizontal whitespace character _ ##gray|//Ruby://## hex digit||##gray|//PHP://## [ \t] _ ##gray|//Ruby://## [0-9a-fA-F] || ||\H||##gray|//PHP://## not a horizontal whitespace character _ ##gray|//Ruby://## not a hex digit||##gray|//PHP://## [^ \t] _ ##gray|//Ruby://## [^0-9a-fA-F] || ||\s||whitespace character||[ \t\r\n\f]|| ||\S||non whitespace character||[^ \t\r\n\f]|| ||\v||vertical whitespace character||[\r\n\f]|| ||\V||not a vertical whitespace character||[^\r\n\f]|| ||\w||word character||[A-Za-z0-9]|| ||\W||non word character||[^A-Za-z0-9]||

alternation and grouping: | ( )

The vertical pipe | is used for alternation and parens () for grouping.

A vertical pipe takes as its arguments everything up to the next vertical pipe, enclosing paren, or end of string.

Parentheses control the scope of alternation and the quantifiers described below. They are also used for capturing groups, which are the substrings which matched parenthesized parts of the regular expression. Each language numbers the groups and provides a mechanism for extracting them when a match is made. A parenthesized subexpression can be removed from the groups with this syntax: {{(?:##gray|//expr//##)}}

quantifiers: * + ? { }

As an argument quantifiers take the preceding regular character, character class, or group. The argument can itself be quantified, so that {{^a{4}*$}} matches strings with the letter a in multiples of 4.

||~ quantifier||~ # of occurrences of argument matched|| ||@@@@||zero or more, greedy|| ||+||one or more, greedy|| ||?||zero or one, greedy|| ||{m,n}||//m// to //n//, greedy|| ||{n}||exactly //n//|| ||{m,}||//m// or more, greedy|| ||{,n}||zero to //n//, greedy|| ||?||zero or more, lazy|| ||+?||one or more, lazy|| ||{m,n}?||//m// to //n//, lazy|| ||{m,}?||//m// or more, lazy|| ||{,n}?||zero to //n//, lazy||

When there is a choice, greedy quantifiers will match the maximum possible number of occurrences of the argument. Lazy quantifiers match the minimum possible number.

anchors: ^ $

||~ anchor||~ matches|| ||^||beginning of a string. In Ruby or when //m// modifier is used also matches right side of a newline|| ||$||end of a string. In Ruby or when //m// modifier is used also matches left side of a newline|| ||\A||beginning of the string|| ||\b||word boundary. In between a \w and a \W character or in between a \w character and the edge of the string|| ||\B||not a word boundary. In between two \w characters or two \W characters|| ||\z||end of the string|| ||\Z||end of the string unless it is a newline, in which case it matches the left side of the terminal newline||

*escaping: *

To match a metacharacter, put a backslash in front of it. To match a backslash use two backslashes.

php:

PHP 5.3 still supports the EREG engine, though the functions which use it are deprecated. These include the {{split}} function and functions which start with {{ereg}}. The preferred functions are {{preg_split}} and the other functions with a {{preg}} prefix.

# regex-literal-note ++ [#regex-literal literal, custom delimited literal]

The literal for a regular expression; the literal for a regular expression with a custom delimiter.

javascript:

The constructor for a regular expression is:

code var rx = RegExp(“lorem|ipsum”); /code

php:

PHP regex literals are strings. The first character is the delimiter and it must also be the last character. If the start delimiter is (, {, or [ the end delimiter must be ), }, or ], respectively.

Here are the signatures from the PHP manual for the preg functions used in this sheet:

code array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

int pregmatchall ( string $pattern , string $subject [, array &$matches [, int $flags = PREGPATTERNORDER [, int $offset = 0 ]]] ) /code

python:

Python does not have a regex literal, but the {{re.compile}} function can be used to create regex objects.

Compiling regexes can always be avoided:

code re.compile(‘\d{4}’).search(‘1999’) re.search(‘\d{4}’, ‘1999’)

re.compile(‘foo’).sub(‘bar’, ‘foo bar’) re.sub(‘foo’, ‘bar’, ‘foo bar’)

re.compile(‘\w+’).findall(‘do re me’) re.findall(‘\w+’, ‘do re me’) /code

# ascii-char-class-abbrev-note ++ [#ascii-char-class-abbrev ascii character class abbreviations]

The supported [#regex-char-class-abbrev character class abbreviations].

Note that {{\h}} refers to horizontal whitespace (i.e. a space or tab) in PHP and a hex digit in Ruby. Similarly {{\H}} refers to something that isn’t horizontal whitespace in PHP and isn’t a hex digit in Ruby.

# unicode-char-class-abbrev-note ++ [#unicode-char-class-abbrev unicode character class abbreviations]

The supported character class abbreviations for sets of Unicode characters.

Each Unicode character belongs to one of these major categories:

||C||Other|| ||L||Letter|| ||M||Mark|| ||N||Number|| ||P||Punctuation|| ||S||Symbol|| ||Z||Separator||

Each major category is subdivided into multiple minor categories. Each minor category has a two letter code, where the first letter is the major category. For example, {{Nd}} is “Number, decimal digit”.

Download [http://www.unicode.org/Public/UNIDATA/UnicodeData.txt UnicodeData.txt] to find out which major and minor category and character belongs to.

# regex-anchors-note ++ [#regex-anchors anchors]

The supported anchors.

# regex-test-note ++ [#regex-test match test]

How to test whether a string matches a regular expression.

python:

The {{re.match}} function returns true only if the regular expression matches the beginning of the string. {{re.search}} returns true if the regular expression matches any substring of the of string.

ruby:

{{match}} is a method of both {{Regexp}} and {{String}} so can match with both

code /1999/.match(“1999”) /code

and

code “1999”.match(/1999/) /code

When variables are involved it is safer to invoke the {{Regexp}} method because string variables are more likely to contain {{nil}}.

# case-insensitive-regex-note ++ [#case-insensitive-regex case insensitive match test]

How to perform a case insensitive match test.

# regex-modifiers-note ++ [#regex-modifiers modifiers]

Modifiers that can be used to adjust the behavior of a regular expression.

The lists are not comprehensive. For all languages except Ruby there are additional modifiers.

||~ modifier||~ behavior|| ||e||##gray|//PHP://## when used with preg_replace, the replacement string, after backreferences are substituted, is eval’ed as PHP code and the result is used as the replacement.|| ||g||##gray|//JavaScript://## read all non-overlapping matches into an array.|| ||i, re.I||##gray|//all://## ignores case. Upper case letters match lower case letters and vice versa.|| ||m, re.M||##gray|//JavaScript, PHP, Python://## makes the ^ and $ match the right and left edge of newlines in addition to the beginning and end of the string. _ ##gray|//Ruby://## makes the period . match newline characters.|| ||o||##gray|//Ruby://## performs variable interpolation #{ } only once per execution of the program.|| ||s, re.S||##gray|//PHP, Python://## makes the period . match newline characters.|| ||x, re.X||##gray|//all://## ignores whitespace (outside of [] character classes) and #-style comments in the regex.||

python:

Python modifiers are bit flags. To use more than one flag at the same time, join them with bit or: |

There are alternative identifiers for the modifiers:

||re.A||re.ASCII|| ||re.I||re.IGNORECASE|| ||re.M||re.MULTILINE|| ||re.S||re.DOTALL|| ||re.X||re.VERBOSE||

# subst-note ++ [#subst substitution]

How to replace all occurrences of a matching pattern in a string with the provided substitution string.

php:

The number of occurrences replaced can be controlled with a 4th argument to {{preg_replace}}:

code $s = “foo bar bar”; preg_replace(‘/bar/’, “baz”, $s, 1); /code

If no 4th argument is provided, all occurrences are replaced.

python:

The 3rd argument to {{sub}} controls the number of occurrences which are replaced.

code s = ‘foo bar bar’ re.compile(‘bar’).sub(‘baz’, s, 1) /code

If there is no 3rd argument, all occurrences are replaced.

ruby:

The //gsub// operator returns a copy of the string with the substitution made, if any. The //gsub!// performs the substitution on the original string and returns the modified string.

The //sub// and //sub!// operators only replace the first occurrence of the match pattern.

# match-prematch-postmatch-note ++ [#match-prematch-postmatch match, prematch, postmatch]

How to get the substring that matched the regular expression, as well as the part of the string before and after the matching substring.

ruby:

The special variables {{$&}}, {{$@@`@@}}, and {{$’}} also contain the match, prematch, and postmatch.

# group-capture-note ++ [#group-capture group capture]

How to get the substrings which matched the parenthesized parts of a regular expression.

ruby:

Ruby has syntax for extracting a group from a match in a single expression. The following evaluates to “1999”:

code “1999-07-08”[/(\d{4})-(\d{2})-(\d{2})/, 1] /code

# named-group-capture-note ++ [#named-group-capture named group capture]

How to get the substrings which matched the parenthesized parts of a regular expression and put them into a dictionary.

For reference, we call the {{(?P@@…@@)}} notation //Python-style// and the {{(?@@…@@)}} notation //Perl-style//.

php:

PHP originally supported Python-style named groups since that was the style that was added to the PCRE regex engine. Perl-style named groups were added to PHP 5.2.

python:

The Python interpreter was the first to support named groups.

# scan-note ++ [#scan scan]

How to return all non-overlapping substrings which match a regular expression as an array.

# backreference-note ++ [#backreference backreference in match and substitution]

How to use backreferences in a regex; how to use backreferences in the replacement string of substitution.

# recursive-regex-note ++ [#recursive-regex recursive regex]

An examples of a recursive regex.

The example matches substrings containing balanced parens.

# dates-time-note + [#dates-time Date and Time]

In ISO 8601 terminology, a //date// specifies a day in the Gregorian calendar and a //time// does not contain date information; it merely specifies a time of day. A data type which combines both date and time information is convenient, but ISO 8601 doesn’t provide a name for such an entity. PHP, Python, and C# use the compound noun //datetime// for combined date and time values and we adopt it here as a generic term.

An useful property of [http://en.wikipedia.org/wiki/ISO_8601 ISO 8601 dates, times, and datetimes] is that they are correctly ordered by a lexical sort on their string representations. This is because they are big-endian (the year is the leftmost element) and they used fixed-length, zero-padded fields with numerical values for each term in the string representation.

The C standard library provides two methods for representing dates. The first is the //Unix epoch//, which is the seconds since the beginning of January 1, 1970 in UTC. If such a time were stored in a 32-bit signed integer, the rollover would happen on January 18, 2038. The Unix epoch is an example of a //serial datetime//, in which the value is stored as a single numeric value representing the difference in time in some unit from a specially designated datetime called the epoch.

Another serial datetime is the //Windows file time//, which is the number of 100 nanosecond intervals since the beginning of January 1, 1601 UTC. It was introduced when journaling was added to NTFS as part of the Windows 2000 launch.

Some serial datetimes use days as the unit. The Excel //serial number// is the number of days since December 31, 1899. The //Julian day number//, used in astronomy, is the number of days since November 24, 4714 BCE in the proleptic Gregorian calendar. Julian days start at noon GMT.

A //broken-down datetime// uses multiple numeric values to represent the components of a calendar date and time. An example from the C standard library is the {{tm}} struct, a definition of which can be found on Unix systems in {{/usr/include/time.h}}:

code struct tm { int tmsec; /* seconds after the minute [0-60] */ int tmmin; /* minutes after the hour [0-59] / int tm_hour; / hours since midnight [0-23] / int tm_mday; / day of the month [1-31] / int tm_mon; / months since January [0-11] / int tm_year; / years since 1900 / int tm_wday; / days since Sunday [0-6] / int tm_yday; / days since January 1 [0-365] / int tm_isdst; / Daylight Savings Time flag / long tm_gmtoff; / offset from CUT in seconds */ char tm_zone; / timezone abbreviation */ }; /code

The Linux man pages call the {{tm}} struct a “broken-down” date and time, whereas the BSD man pages call it a “broken-out” date and time.

The first day in the Gregorian calendar was 15 October 1582. The //proleptic Gregorian calendar// is an extension of the Gregorian calendar to earlier dates. When such dates are used, they should be called out to be precise. The epoch in the proleptic Gregorian calendar is the year 0001, also written 1 AD or 1 CE. The previous year is the year 0000, also written 1 BC or 1 BCE. The year before that is the year -0001, also written 2 BC or 2 BCE. The ISO 8601 standard recommends that years before 0000 or after 9999 be written with a plus or minus sign prefix.

An //ordinal date// is a broken-down date consisting of a year, followed by the day of the year. The ISO 8601 standard recommends that it be written in {{YYYY-DDD}} or {{YYYYDDD}} format. The corresponding {{strftime}} formats are {{%Y-%j}} and {{%Y%j}}.

A //week date// is a type of calendar which uses the year, week of the year, and day of the week to refer to to dates. In the ISO 8601 week date, the first week of the year is the week starting from Monday which contains January 4th. An ISO 8601 week date can thus have a different year number than the corresponding Gregorian date. The first week of the year is numbered {{01}}, and the first day of the week, Monday, is numbered {{1}}. Weeks are written in {{YYYY-Www-D}} or {{YYYYWwwD}} format, where the upper case W is literal. The corresponding {{strftime}} literals are {{%G-W%V-%u}} and {{%GW%V%u}}.

Common years have 365 days and leap years have 366 days. The extra day in February 29th. Leap years are years divisible by 4 but not 100, or years divisible by 400.

In 1967, the definition of a second was changed from 1/86,400 of a solar day to a value expressed in terms of radiation produced by 133Cs. Because the length of a solar day is irregular, leap seconds are occasionally used to keep things in sync. This is accomplished by occasionally adding a leap second to the end of June 30th or December 31st. The system also allows for removing the last second of June 30th or December 31st, though as of 2014 this hasn’t been done.

# broken-down-datetime-type-note ++ [#broken-down-datetime-type broken-down datetime type]

The data type used to hold a combined date and time.

python:

Python uses and exposes the {{tm}} struct of the C standard library. Python has a module called {{time}} which is a thin wrapper to the standard library functions which operate on this struct. Here is how get a {{tm}} struct in Python:

code import time

utc = time.gmtime(time.time()) t = time.localtime(time.time()) /code

# current-datetime-note ++ [#current-datetime current datetime]

How to get the combined date and time for the present moment in both local time and UTC.

# current-unix-epoch-note ++ [#current-unix-epoch current unix epoch]

How to get the current time as a Unix epoch timestamp.

# broken-down-datetime-to-unix-epoch-note ++ [#broken-down-datetime-to-unix-epoch broken-down datetime to unix epoch]

How to convert a datetime type to the Unix epoch which is the number of seconds since the start of January 1, 1970 UTC.

python:

The Python datetime object created by {{now()}} and {{utcnow()}} has no timezone information associated with it. The {{strftime()}} method assumes a receiver with no time zone information represents a local time. Thus it is an error to call {{strftime()}} on the return value of {{utcnow()}}.

Here are two different ways to get the current Unix epoch. The second way is faster:

code import calendar import datetime

int(datetime.datetime.now().strftime(‘%s’)) calendar.timegm(datetime.datetime.utcnow().utctimetuple()) /code

Replacing {{now()}} with {{utcnow()}} in the first way, or {{utcnow()}} with {{now()}} in the second way produces an incorrect value.

# unix-epoch-to-broken-down-datetime-note ++ [#unix-epoch-to-broken-down-datetime unix epoch to broken-down datetime]

How to convert the Unix epoch to a broken-down datetime.

# fmt-datetime-note ++ [#fmt-datetime format datetime]

How to format a datetime as a string using using a string of format specifiers.

The format specifiers used by the {{strftime}} function from the standard C library and the Unix {{date}} command:

||~ ||~ numeric||~ alphanumeric||~ notes|| ||year||%Y %C%y|| ||%C and %y are the first two and last two digits of a 4 digit year|| ||month||%m||%B %b %h||%m is zero padded in {01, …, 12} _ %h is blank padded in {1, …, 12}|| ||day of month||%d %e|| ||%d is zero padded in {01, …, 31} _ %e is blank padded in {1, …, 31}|| ||hour||%H %k||%I%p %l%p||%H and %k are in zero and blank padded|| ||minute||%M|| ||%M is zero padded in the range {00, …, 59}|| ||second||%S|| ||%S is zero padded, due to leap seconds it is in the range {00, …, 60}|| ||day of year||%j|| ||%j is zero padded in the range {000, …, 366}|| ||week date year||%G %g|| ||the ISO 8601 week date year. Used with %V and %u.|| ||week of year||%V %U %W|| ||%V is the ISO 8601 week of year. In {01, 53}. Used with %G _ %U is the week number when Sunday starts the week. In {00, 53}. Used with %Y and %C%y. _ %W is the week number when Monday starts the week. In {00, 53}. Used with %Y and %C%y.|| ||day of week||%u %w||%A %a||%u is in {{1, …, 7} starting at Monday _ %w is in {0, …, 6} starting at Sunday|| ||unix epoch||%s|| || || ||date||%D %F %x||%v||%D is %m/%d/%y _ %F is %Y-%m-%d _ %x locale dependent; same as %D in US|| ||time||%T %R %X||%r||%T is %H:%M:%S _ %R is %H:%M _ %X is locale dependent; same as %T in US _ %r is %I:%M:%S %p|| ||date and time|| ||%c||locale dependent|| ||date, time, and tmz|| ||%+||locale dependent|| ||time zone name|| ||%Z||the ambiguous 3 letter abbrevation; e.g. “PST”|| ||time zone offset||%z|| ||”-0800” for Pacific Standard Time|| ||percent sign|| ||%%|| || ||newline|| ||%n|| || ||tab|| ||%t|| ||

php:

PHP supports strftime but it also has its own time formatting system used by {{date}}, {{DateTime::format}}, and {{DateTime::createFromFormat}}. The letters used in the PHP time formatting system are [http://www.php.net/manual/en/datetime.createfromformat.php described here].

# parse-datetime-note ++ [#parse-datetime parse datetime]

How to parse a datetime using the format notation of the {{strptime}} function from the standard C library.

# parse-datetime-without-fmt-note ++ [#parse-datetime-without-fmt parse datetime w/o format]

How to parse a date without providing a format string.

# date-parts-note ++ [#date-parts date parts]

How to get the year, month, and day of month from a datetime.

# time-parts-note ++ [#time-parts time parts]

How to the hour, minute, and second from a datetime.

# build-datetime-note ++ [#build-datetime build broken-down datetime]

How to build a broken-down datetime from the date parts and the time parts.

# datetime-subtraction-note ++ [#datetime-subtraction datetime subtraction]

The data type that results when subtraction is performed on two combined date and time values.

# add-duration-note ++ [#add-duration add duration]

How to add a duration to a datetime.

A duration can easily be added to a datetime value when the value is a Unix epoch value.

ISO 8601 distinguishes between a time interval, which is defined by two datetime endpoints, and a duration, which is the length of a time interval and can be defined by a unit of time such as ‘10 minutes’. A time interval can also be defined by date and time representing the start of the interval and a duration.

ISO 8601 defines [http://en.wikipedia.org/wiki/ISO_8601#Durations notation for durations]. This notation starts with a ‘P’ and uses a ‘T’ to separate the day and larger units from the hour and smaller units. Observing the location relative to the ‘T’ is important for interpreting the letter ‘M’, which is used for both months and minutes.

# local-tmz-determination-note ++ [#local-tmz-determination local time zone determination]

Do datetime values include time zone information. When a datetime value for the local time is created, how the local time zone is determined.

On Unix systems processes determine the local time zone by inspecting the binary file {{/etc/localtime}}. To examine it from the command line use {{zdump}}:

code $ zdump /etc/localtime /etc/localtime Tue Dec 30 10:03:27 2014 PST /code

On Windows the time zone name is stored in the registry at {{HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation\TimeZoneKeyName}}.

php:

The default time zone can also be set in the {{php.ini}} file.

code date.timezone = “America/Los_Angeles” /code

Here is the list of [http://php.net/timezones timezones supported by PHP].

# nonlocal-tmz-note ++ [#nonlocal-tmz nonlocal time zone]

How to convert a datetime to the equivalent datetime in an arbitrary time zone.

# tmz-info-note ++ [#tmz-info time zone info]

How to get the name of the time zone and the offset in hours from UTC.

Timezones are often identified by [http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations three or four letter abbreviations]. Many of the abbreviations do not uniquely identify a time zone. Furthermore many of the time zones have been altered in the past. The http://en.wikipedia.org/wiki/Tz_database Olson database decomposes the world into zones in which the local clocks have all been set to the same time since 1970; it gives these zones unique names.

ruby:

The {{Time}} class has a {{zone}} method which returns the time zone abbreviation for the object. There is a {{tzinfo}} gem which can be used to create time zone objects using the Olson database name. This can in turn be used to convert between UTC times and local times which are daylight saving aware.

# daylight-savings-test-note ++ [#daylight-savings-test daylight savings test]

Is a datetime in daylight savings time?

# microseconds-note ++ [#microseconds microseconds]

How to get the microseconds component of a combined date and time value. The SI abbreviations for milliseconds and microseconds are {{ms}} and {{@<μ>@s}}, respectively. The C standard library uses the letter {{u}} as an abbreviation for {{micro}}. Here is a struct defined in {{/usr/include/sys/time.h}}:

code struct timeval { timet tvsec; /* seconds since Jan. 1, 1970 / susecondst tvusec; / and microseconds */ }; /code

# sleep-note ++ [#sleep sleep]

How to put the process to sleep for a specified number of seconds. In Python and Ruby the default version of {{sleep}} supports a fractional number of seconds.

php:

PHP provides {{usleep}} which takes an argument in microseconds:

code usleep(500000); /code

# timeout-note ++ [#timeout timeout]

How to cause a process to timeout if it takes too long.

Techniques relying on SIGALRM only work on Unix systems.

# arrays-note + [#arrays Arrays]

What the languages call their basic container types:

||~ ||~ javascript||~ php||~ python||~ ruby|| ||[#array-literal array]|| ||array||list, tuple, sequence||Array, Enumerable|| ||[#dict-literal dictionary]|| ||array||dict, mapping||Hash||

javascript:

php:

PHP uses the same data structure for arrays and dictionaries.

python:

Python has the mutable //list// and the immutable //tuple//. Both are //sequences//. To be a //sequence//, a class must implement @@getitem@@, @@setitem@@, @@delitem@@, @@len@@, @@contains@@, @@iter@@, @@add@@, @@mul@@, @@radd@@, and @@rmul@@.

ruby:

Ruby provides an //Array// datatype. If a class defines an //each// iterator and a comparison operator <=>, then it can mix in the //Enumerable// module.

# array-literal-note ++ [#array-literal literal]

Array literal syntax.

ruby:

The {{%w}} operator splits the following string on whitespace and creates an array of strings from the words. The character following the {{%w}} is the string delimiter. If the following character is (, [, or {, then the character which terminates the string must be ), ], or }.

The {{%W}} operator is like the {{%w}} operator, except that double-quote style {{#{ } }} expressions will be interpolated.

# quote-words-note ++ [#quote-words quote words]

The quote words operator, which is a literal for arrays of strings where each string contains a single word.

# array-size-note ++ [#array-size size]

How to get the number of elements in an array.

# array-empty-note ++ [#array-empty empty test]

How to test whether an array is empty.

# array-lookup-note ++ [#array-lookup lookup]

How to access a value in an array by index.

python:

A negative index refers to the //length - index// element.

code

a = [1, 2, 3] a[-1] 3 /code

ruby:

A negative index refers to to the //length - index// element.

# array-update-note ++ [#array-update update]

How to update the value at an index.

# array-out-of-bounds-note ++ [#array-out-of-bounds out-of-bounds behavior]

What happens when the value at an out-of-bounds index is referenced.

# array-element-index-note ++ [#array-element-index element index]

How to get the index of an element in an array.

php:

Setting the 3rd argument of {{array_search}} to true makes the search use {{===}} for an equality test. Otherwise the {{==}} test is performed, which makes use of implicit type conversions.

# array-slice-note ++ [#array-slice slice]

How to slice a subarray from an array by specifying a start index and an end index; how to slice a subarray from an array by specifying an offset index and a length index.

python:

Slices can leave the first or last index unspecified, in which case the first or last index of the sequence is used:

code

a=[1, 2, 3, 4, 5] a[:3] [1, 2, 3] /code

Python has notation for taking every nth element:

code

a=[1, 2, 3, 4, 5] a[::2] [1, 3, 5] /code

The third argument in the colon-delimited slice argument can be negative, which reverses the order of the result:

code

a = [1, 2, 3, 4] a[::-1] [4, 3, 2, 1] /code

# array-slice-to-end-note ++ [#array-slice-to-end slice to end]

How to slice to the end of an array.

The examples take all but the first element of the array.

# array-back-note ++ [#array-back manipulate back]

How to add and remove elements from the back or high index end of an array.

These operations can be used to use the array as a stack.

# array-front-note ++ [#array-front manipulate front]

How to add and remove elements from the front or low index end of an array.

These operations can be used to use the array as a stack. They can be used with the operations that manipulate the back of the array to use the array as a queue.

# array-concatenation-note ++ [#array-concatenation concatenate]

How to create an array by concatenating two arrays; how to modify an array by concatenating another array to the end of it.

# replicate-array-note ++ [#replicate-array replicate]

How to create an array containing the same value replicated //n// times.

# array-copy-note ++ [#array-copy copy]

How to make an address copy, a shallow copy, and a deep copy of an array.

After an address copy is made, modifications to the copy also modify the original array.

After a shallow copy is made, the addition, removal, or replacement of elements in the copy does not modify of the original array. However, if elements in the copy are modified, those elements are also modified in the original array.

A deep copy is a recursive copy. The original array is copied and a deep copy is performed on all elements of the array. No change to the contents of the copy will modify the contents of the original array.

python:

The slice operator can be used to make a shallow copy:

code a2 = a[:] /code

{{list(v)}} always returns a list, but {{v[:]}} returns a value of the same as {{v}}. The slice operator can be used in this manner on strings and tuples but there is little incentive to do so since both are immutable.

{{copy.copy}} can be used to make a shallow copy on types that don’t support the slice operator such as a dictionary. Like the slice operator {{copy.copy}} returns a value with the same type as the argument.

# array-as-func-arg-note ++ [#array-as-func-arg array as function argument]

How an array is passed to a function when provided as an argument.

# iterate-over-array-note ++ [#iterate-over-array iterate over elements]

How to iterate over the elements of an array.

# indexed-array-iteration-note ++ [#indexed-array-iteration iterate over indices and elements]

How to iterate over the element-index pairs.

# range-iteration-note ++ [#range-iteration iterate over range]

Iterate over a range without instantiating it as a list.

# range-array-note ++ [#range-array instantiate range as array]

How to convert a range to an array.

Python 3 ranges and Ruby ranges implement some of the functionality of arrays without allocating space to hold all the elements.

python:

In Python 2 {{range()}} returns a list.

In Python 3 {{range()}} returns an object which implements the immutable sequence API.

ruby:

The Range class includes the Enumerable module.

# array-reverse-note ++ [#array-reverse reverse]

How to create a reversed copy of an array, and how to reverse an array in place.

python:

{{reversed}} returns an iterator which can be used in a {{for/in}} construct:

code print(“counting down:”) for i in reversed([1, 2, 3]): print(i) /code

{{reversed}} can be used to create a reversed list:

code a = list(reversed([1, 2, 3])) /code

# array-sort-note ++ [#array-sort sort]

How to create a sorted copy of an array, and how to sort an array in place. Also, how to set the comparison function when sorting.

php:

{{usort}} sorts an array in place and accepts a comparison function as a 2nd argument:

code function cmp($x, $y) { $lx = strtolower($x); $ly = strtolower($y); if ( $lx < $ly ) { return -1; } if ( $lx == $ly ) { return 0; } return 1; }

$a = [“b”, “A”, “a”, “B”];

usort($a, “cmp”); /code

python:

In Python 2 it is possible to specify a binary comparision function when calling {{sort}}:

code a = [(1, 3), (2, 2), (3, 1)]

a.sort(cmp=lambda a, b: -1 if a[1] < b[1] else 1)

a now contains:

[(3, 1), (2, 2), (1, 3)] /code

In Python 3 the {{cmp}} parameter was removed. One can achieve the same effect by defining {{cmp}} method on the class of the list element.

# array-dedupe-note ++ [#array-dedupe dedupe]

How to remove extra occurrences of elements from an array.

python:

Python sets support the {{len}}, {{in}}, and {{for}} operators. It may be more efficient to work with the result of the set constructor directly rather than convert it back to a list.

# membership-note ++ [#membership membership]

How to test for membership in an array.

# intersection-note ++ [#intersection intersection]

How to compute an intersection.

python:

Python has literal notation for sets:

code {1, 2, 3} /code

Use {{set}} and {{list}} to convert lists to sets and vice versa:

code a = list({1, 2, 3}) ensemble = set([1, 2, 3]) /code

ruby:

The intersect operator {{&}} always produces an array with no duplicates.

# union-note ++ [#union union]

ruby:

The union operator {{|}} always produces an array with no duplicates.

# set-diff-note ++ [#set-diff relative complement, symmetric difference]

How to compute the relative complement of two arrays or sets; how to compute the symmetric difference.

ruby:

If an element is in the right argument, then it will not be in the return value even if it is contained in the left argument multiple times.

# map-note ++ [#map map]

Create an array by applying a function to each element of a source array.

ruby:

The {{map!}} method applies the function to the elements of the array in place.

{{collect}} and {{collect!}} are synonyms for {{map}} and {{map!}}.

# filter-note ++ [#filter filter]

Create an array containing the elements of a source array which match a predicate.

ruby:

The in place version is {{select!}}.

{{reject}} returns the complement of {{select}}. {{reject!}} is the in place version.

The {{partition}} method returns two arrays:

code a = [1, 2, 3] lt2, ge2 = a.partition { |n| n < 2 } /code

# reduce-note ++ [#reduce reduce]

Return the result of applying a binary operator to all the elements of the array.

python:

{{reduce}} is not needed to sum a list of numbers:

code sum([1, 2, 3]) /code

ruby:

The code for the reduction step can be provided by name. The name can be a symbol or a string:

code [1, 2, 3].inject(:+)

[1, 2, 3].inject(“+”)

[1, 2, 3].inject(0, :+)

[1, 2, 3].inject(0, “+”) /code

# universal-existential-test-note ++ [#universal-existential-test universal and existential tests]

How to test whether a condition holds for all members of an array; how to test whether a condition holds for at least one member of any array.

A universal test is always true for an empty array. An existential test is always false for an empty array.

A existential test can readily be implemented with a filter. A universal test can also be implemented with a filter, but it is more work: one must set the condition of the filter to the negation of the predicate and test whether the result is empty.

# shuffle-sample-note ++ [#shuffle-sample shuffle and sample]

How to shuffle an array. How to extract a random sample from an array.

php:

The {{array_rand}} function returns a random sample of the indices of an array. The result can easily be converted to a random sample of array values:

code $a = [1, 2, 3, 4]; $sample = []; foreach (arrayrand($a, 2) as $i) { arraypush($sample, $a[$i]); } /code

# flatten-note ++ [#flatten flatten]

How to flatten nested arrays by one level or completely.

When nested arrays are flattened by one level, the depth of each element which is not in the top level array is reduced by one.

Flattening nested arrays completely leaves no nested arrays. This is equivalent to extracting the leaf nodes of a tree.

php, python:

To flatten by one level use reduce. Remember to handle the case where an element is not array.

To flatten completely write a recursive function.

# zip-note ++ [#zip zip]

How to interleave arrays. In the case of two arrays the result is an array of pairs or an associative list.

# dictionaries-note + [#dictionaries Dictionaries]

# dict-literal-note ++ [#dict-literal literal]

The syntax for a dictionary literal.

# dict-size-note ++ [#dict-size size]

How to get the number of dictionary keys in a dictionary.

# dict-lookup-note ++ [#dict-lookup lookup]

How to lookup a dictionary value using a dictionary key.

# dict-missing-key-note ++ [#dict-missing-key missing key behavior]

What happens when a lookup is performed on a key that is not in a dictionary.

python:

Use {{dict.get()}} to avoid handling {{KeyError}} exceptions:

code d = {} d.get(‘lorem’) # returns None d.get(‘lorem’, ‘‘) # returns ‘‘ /code

# dict-key-check-note ++ [#dict-key-check is key present]

How to check for the presence of a key in a dictionary without raising an exception. Distinguishes from the case where the key is present but mapped to null or a value which evaluates to false.

# dict-delete-note ++ [#dict-delete delete]

How to remove a key/value pair from a dictionary.

# dict-assoc-array-note ++ [#dict-assoc-array from array of pairs, from even length array]

How to create a dictionary from an array of pairs; how to create a dictionary from an even length array.

# dict-merge-note ++ [#dict-merge merge]

How to merge the values of two dictionaries.

In the examples, if the dictionaries {{d1}} and {{d2}} share keys then the values from {{d2}} will be used in the merged dictionary.

# dict-invert-note ++ [#dict-invert invert]

How to turn a dictionary into its inverse. If a key ‘foo’ is mapped to value ‘bar’ by a dictionary, then its inverse will map the key ‘bar’ to the value ‘foo’. However, if multiple keys are mapped to the same value in the original dictionary, then some of the keys will be discarded in the inverse.

# dict-iter-note ++ [#dict-iter iteration]

How to iterate through the key/value pairs in a dictionary.

python:

In Python 2.7 {{dict.items()}} returns a list of pairs and {{dict.iteritems()}} returns an iterator on the list of pairs.

In Python 3 {{dict.items()}} returns an iterator and {{dict.iteritems()}} has been removed.

# dict-key-val-note ++ [#dict-key-val keys and values as arrays]

How to convert the keys of a dictionary to an array; how to convert the values of a dictionary to an array.

python:

In Python 3 {{dict.keys()}} and {{dict.values()}} return read-only views into the dict. The following code illustrates the change in behavior:

code d = {} keys = d.keys() d[‘foo’] = ‘bar’

if ‘foo’ in keys: print(‘running Python 3’) else: print(‘running Python 2’) /code

# dict-sort-values-note ++ [#dict-sort-values sort by values]

How to iterate through the key-value pairs in the order of the values.

# dict-default-val-note ++ [#dict-default-val default value, computed value]

How to create a dictionary with a default value for missing keys; how to compute and store the value on lookup.

php:

Extend {{ArrayObject}} to compute values on lookup:

code class Factorial extends ArrayObject {

public function offsetExists($i) { return true; }

public function offsetGet($i) { if(!parent::offsetExists($i)) { if ( $i < 2 ) { parent::offsetSet($i, 1); } else { $n = $this->offsetGet($i-1); parent::offsetSet($i, $i*$n); } } return parent::offsetGet($i); } }

$factorial = new Factorial(); /code

# functions-note + [#functions Functions]

Python has both functions and methods. Ruby only has methods: functions defined at the top level are in fact methods on a special main object. Perl subroutines can be invoked with a function syntax or a method syntax.

# def-func-note ++ [#def-func define]

How to define a function.

# invoke-func-note ++ [#invoke-func invoke]

How to invoke a function.

python:

Parens are mandatory, even for functions which take no arguments. Omitting the parens returns the function or method as an object. Whitespace can occur between the function name and the following left paren.

In Python 3 print is a function instead of a keyword; parens are mandatory around the argument.

ruby:

Ruby parens are optional. Leaving out the parens results in ambiguity when function invocations are nested. The interpreter resolves the ambiguity by assigning as many arguments as possible to the innermost function invocation, regardless of its actual arity. It is mandatory that the left paren not be separated from the method name by whitespace.

# apply-func-note ++ [#apply-func apply function to array]

How to apply a function to an array.

perl:

Perl passes the elements of arrays as individual arguments. In the following invocation, the function {{foo()}} does not know which arguments came from which array. For that matter it does not know how many arrays were used in the invocation:

code foo(@a, @b); /code

If the elements must be kept in their respective arrays the arrays must be passed by reference:

code sub foo { my @a = @{$[0]}; my @b = @{$[1]}; }

foo(\@a, \@b); /code

When hashes are used as arguments, each key and value becomes its own argument.

# missing-arg-note ++ [#missing-arg missing argument behavior]

What happens when a function is invoked with too few arguments.

# extra-arg-note ++ [#extra-arg extra argument behavior]

What happens when a function is invoked with too many arguments.

# default-arg-note ++ [#default-arg default argument]

How to declare a default value for an argument.

# variadic-func-note ++ [#variadic-func variadic function]

How to write a function which accepts a variable number of argument.

python:

This function accepts one or more arguments. Invoking it without any arguments raises a {{TypeError}}:

code def poker(dealer, *players): … /code

ruby:

This function accepts one or more arguments. Invoking it without any arguments raises an {{ArgumentError}}:

code def poker(dealer, *players) … end /code

# param-alias-note ++ [#param-alias parameter alias]

How to make a parameter an alias of a variable in the caller.

# named-param-note ++ [#named-param named parameters]

How to write a function which uses named parameters and how to invoke it.

python:

The caller can use named parameter syntax at the point of invocation even if the function was defined using positional parameters.

The splat operator * collects the remaining arguments into a list. In a function invocation, the splat can be used to expand an array into separate arguments.

The double splat operator ** collects named parameters into a dictionary. In a function invocation, the double splat expands a dictionary into named parameters.

A double splat operator can be used to force the caller to use named parameter syntax. This method has the disadvantage that spelling errors in the parameter name are not caught:

code def fequal(x, y, **kwargs): eps = opts.get(‘eps’) or 0.01 return abs(x - y) < eps /code

In Python 3 named parameters can be made mandatory:

code def fequal(x, y, *, eps): return abs(x-y) < eps

fequal(1.0, 1.001, eps=0.01) # True

fequal(1.0, 1.001) # raises TypeError /code

ruby:

In Ruby 2.1 named parameters can be made mandatory:

code def fequals(x, y, eps:) (x - y).abs < eps end

false:

fequals(1.0, 1.001, eps: 0.1**10)

ArgumentError:

fequals(1.0, 1.001) /code

# retval-note ++ [#retval return value]

How the return value of a function is determined.

# multiple-retval-note ++ [#multiple-retval multiple return values]

How to return multiple values from a function.

# anonymous-func-literal-note ++ [#anonymous-func-literal anonymous function literal]

The syntax for an anonymous function literal; i.e. a lambda function.

python:

Python lambdas cannot contain newlines or semicolons, and thus are limited to a single statement or expression. Unlike named functions, the value of the last statement or expression is returned, and a //return// is not necessary or permitted. Lambdas are closures and can refer to local variables in scope, even if they are returned from that scope.

If a closure function is needed that contains more than one statement, use a nested function:

code def make_nest(x): b = 37 def nest(y): c = x*y c *= b return c return nest

n = make_nest(12*2) print(n(23)) /code

Python closures are read only.

A nested function can be returned and hence be invoked outside of its containing function, but it is not visible by its name outside of its containing function.

ruby:

The following lambda and Proc object behave identically:

code sqr = lambda { |x| x * x }

sqr = Proc.new {|x| x * x } /code

With respect to control words, Proc objects behave like blocks and lambdas like functions. In particular, when the body of a Proc object contains a {{return}} or {{break}} statement, it acts like a {{return}} or {{break}} in the code which invoked the Proc object. A {{return}} in a lambda merely causes the lambda to exit, and a {{break}} inside a lambda must be inside an appropriate control structure contained with the lambda body.

Ruby are alternate syntax for defining lambdas and invoking them:

code sqr = ->(x) {x*x}

sqr.(2) /code

# invoke-anonymous-func-note ++ [#invoke-anonymous-func invoke anonymous function]

The syntax for invoking an anonymous function.

# func-as-val-note ++ [#func-as-val function as value]

How to store a function in a variable and pass it as an argument.

php:

If a variable containing a string is used like a function then PHP will look for a function with the name in the string and attempt to invoke it.

python:

Python function are stored in variables by default. As a result a function and a variable with the same name cannot share the same scope. This is also the reason parens are mandatory when invoking Python functions.

# private-state-func-note ++ [#private-state-func function with private state]

How to create a function with private state which persists between function invocations.

python:

Here is a technique for creating private state which exploits the fact that the expression for a default value is evaluated only once:

code def counter(_state=[0]): _state[0] += 1 return _state[0]

print(counter()) /code

# closure-note ++ [#closure closure]

How to create a first class function with access to the local variables of the local scope in which it was created.

python:

Python 2 has limited closures: access to local variables in the containing scope is read only and the bodies of anonymous functions must consist of a single expression.

Python 3 permits write access to local variables outside the immediate scope when declared with {{nonlocal}}.

# generator-note ++ [#generator generator]

How to create a function which can yield a value back to its caller and suspend execution.

python:

A Python generator is a function which returns an iterator.

An iterator is an object with two methods: {{iter()}}, which returns the iterator itself, and {{next()}}, which returns the next item or raises a {{StopIteration}} exception.

Python sequences, of which lists are an example, define an {{iter()}} for returned an iterator which traverses the sequence.

Python iterators can be used in //for/in// statements and list comprehensions.

In the table below, {{p}} and {{q}} are variables for iterators.

||||~ itertools|| ||~ generator||~ description|| ||count(start=0, step=1)||arithmetic sequence of integers|| ||cyle(p)||cycle over {{p}} endlessly|| ||repeat(v, [n])||return {{v}} {{n}} times, or endlessly|| ||chain(p, q)||{{p}} followed by {{q}}|| ||compress(p, q)||{{p}} if {{q}}|| ||groupby(p, func)|| || ||ifilter(pred, p)||{{p}} if {{pred(p)}}|| ||ifilterfalse(pred, p)||{{p}} if not {{pred(p)}}|| ||islice(p, [start], stop, [step])|| || ||imap|| || ||starmap()|| || ||tee()|| || ||takewhile()|| || ||izip()|| || ||iziplongest()|| || ||product()|| || ||permutations()|| || ||combinations()|| || ||combinationswith_replacement()|| ||

ruby:

Ruby generators are called fibers.

# decorator-note ++ [#decorator decorator]

A decorator replaces an invocation of one function with another in a way that that is imperceptible to the client.

Normally a decorator will add a small amount of functionality to the original function which it invokes. A decorator can modify the arguments before passing them to the original function or modify the return value before returning it to the client. Or it can leave the arguments and return value unmodified but perform a side effect such as logging the call.

# invoke-op-like-func-note ++ [#invoke-op-like-func invoke operator like function]

How to call an operator using the function invocation syntax.

This is useful when dealing with an API which accepts a function as an argument.

python:

The {{operator}} module provides functions which perform the same operations as the various operators. Using these functions is more efficient than wrapping the operators in lambdas.

ruby:

All operators can be invoked with method invocation syntax. The binary operator invocation syntax can be regarded as syntactic sugar.

# execution-control-note + [#execution-control Execution Control]

# if-note ++ [#if if]

The conditional branch statement.

php:

PHP has the following alternate syntax for {{if}} statements:

code if ($n == 0): echo “no hits\n”; elseif ($n == 1): echo “one hit\n”; else: echo “$n hits\n”; endif; /code

ruby:

If an {{if}} statement is the last statement executed in a function, the return value is the value of the branch that executed.

Ruby {{if}} statements are expressions. They can be used on the right hand side of assignments:

code m = if n 1 else 0 end /code

# switch-note ++ [#switch switch]

A statement which branches based on the value of an expression.

# while-note ++ [#while while]

How to loop over a block while a condition is true.

php:

PHP provides a {{do-while}} loop. The body of such a loop is guaranteed to execute at least once.

code $i = 0; do { echo $i; } while ($i > 0); /code

ruby:

Ruby provides a loop with no exit condition:

code def yes(expletive="y”) loop do puts expletive end end /code

Ruby also provides the {{until}} loop.

Ruby loops can be used in expression contexts but they always evaluate to {{nil}}.

# for-note ++ [#for for]

How to write a C-style for loop.

# break-note ++ [#break break]

A {{break}} statement exits a {{while}} or {{for}} loop immediately.

# continue-note ++ [#continue continue]

A {{continue}} statement skips ahead to the next iteration of a {{while}} or {{for}} loop.

ruby:

There is also a {{redo}} statement, which restarts the current iteration of a loop.

# statement-modifiers-note ++ [#statement-modifiers statement modifiers]

Clauses added to the end of a statement to control execution.

Ruby has conditional statement modifiers. Ruby also has looping statement modifiers.

ruby:

Ruby has the looping statement modifiers {{while}} and {{until}}:

code i = 0 i += 1 while i < 10

j = 10 j -= 1 until j < 0 /code

# exceptions-note + [#exceptions Exceptions]

# base-exc-note ++ [#base-exc base exception]

The base exception type or class that can be used to catch all exceptions.

# predefined-exc-note ++ [#predefined-exc predefined exceptions]

A list of the more commonly encountered exceptions.

python:

Code for inspecting the descendants of a base class:

code def printclasshierarchy(cls, indent=0): print(‘ ‘ * indent, cls.name) for subclass in cls.subclasses(): printclasshierarchy(subclass, indent + 2) /code

The complete Python 3.5 exception hierarchy:

code BaseException Exception TypeError ImportError ZipImportError AssertionError error ArithmeticError FloatingPointError OverflowError ZeroDivisionError SyntaxError IndentationError TabError OSError BlockingIOError TimeoutError PermissionError FileExistsError ConnectionError BrokenPipeError ConnectionAbortedError ConnectionResetError ConnectionRefusedError NotADirectoryError UnsupportedOperation ChildProcessError IsADirectoryError ItimerError InterruptedError FileNotFoundError ProcessLookupError BufferError ReferenceError MemoryError StopIteration StopAsyncIteration Error SystemError CodecRegistryError ValueError UnicodeError UnicodeEncodeError UnicodeDecodeError UnicodeTranslateError UnsupportedOperation NameError UnboundLocalError AttributeError Warning DeprecationWarning SyntaxWarning FutureWarning RuntimeWarning UserWarning UnicodeWarning BytesWarning PendingDeprecationWarning ResourceWarning ImportWarning RuntimeError RecursionError NotImplementedError _DeadlockError LookupError IndexError KeyError CodecRegistryError EOFError GeneratorExit KeyboardInterrupt SystemExit /code

# raise-exc-note ++ [#raise-exc raise exception]

How to raise exceptions.

ruby:

Ruby has a //throw// keyword in addition to //raise//. //throw// can have a symbol as an argument, and will not convert a string to a RuntimeError exception.

# catch-all-handler-note ++ [#catch-all-handler catch-all handler]

How to catch exceptions.

php:

PHP code must specify a variable name for the caught exception. //Exception// is the top of the exception hierarchy and will catch all exceptions.

Internal PHP functions usually do not throw exceptions. They can be converted to exceptions with this signal handler:

code function exceptionerrorhandler($errno, $errstr, $errfile, $errline ) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline); } seterrorhandler(“exceptionerrorhandler”); /code

ruby:

A //rescue Exception// clause will catch any exception. A //rescue// clause with no exception type specified will catch exceptions that are subclasses of //StandardError//. Exceptions outside //StandardError// are usually unrecoverable and hence not handled in code.

In a //rescue// clause, the //retry// keyword will cause the //begin// clause to be re-executed.

In addition to //begin// and //rescue//, ruby has //catch//:

code catch (:done) do loop do retval = work throw :done if retval < 10 end end /code

# re-raise-exc-note ++ [#re-raise-exc re-raise exception]

How to re-raise an exception preserving the original stack trace.

python:

If the exception is assigned to a variable in the {{except}} clause and the variable is used as the argument to {{raise}}, then a new stack trace is created.

ruby:

If the exception is assigned to a variable in the {{rescue}} clause and the variable is used as the argument to {{raise}}, then the original stack trace is preserved.

# last-exc-global-note ++ [#last-exc-global global variable for last exception]

The global variable name for the last exception raised.

# def-exc-note ++ [#def-exc define exception]

How to define a new variable class.

# handle-exc-note ++ [#handle-exc handle exception]

How to catch exceptions of a specific type and assign the exception a name.

php:

PHP exceptions when caught must always be assigned a variable name.

# finally-block-note ++ [#finally-block finally block]

A block of statements that is guaranteed to be executed even if an exception is thrown or caught.

# threads-note + [#threads Threads]

# start-thread-note ++ [#start-thread start thread]

ruby:

Ruby MRI threads are operating system threads, but a global interpreter lock prevents more than one thread from executing Ruby code at a time.

# wait-on-thread-note ++ [#wait-on-thread wait on thread]

How to make a thread wait for another thread to finish.