Notes

Ruby Python PHP JavaScript CoffeeScript CPP


                

                

                

                

                
// C++ is only here to serve as a comparison
// to other languages; on it's own, the C++
// notes are rather incomplete.

Classes

Ruby Python PHP JavaScript CoffeeScript CPP

Class

class ClassName
def meth
# ...
end
end
class ClassName:
def meth(self):
# ...
class ClassName {
public function meth() {
// ...
}
}
// Many ways; this one's used often:
ClassName = function() {
this.meth = function() { /* ... */ }
return this;
};
class ClassName
meth: (args) ->
# ...
class ClassName {
public:
int meth(int args) {
// ...
}
};

Class inheritance

class ClassName < Parent
class ClassName(Parent):
class ClassName extends Parent

                
class ClassName extends Parent
class ClassName : public Parent {
};

Multiple inheritance


                
class ClassName(Parent1, Parent2):

                

                

                
class ClassName : public Parent1,
public Parent2 {};
// Be sure to use `virtual public` if they
// share ancestors

Instantiation

instance = C.new
instance = C.new(args)
instance = C()
instance = C(args)
$instance = new C();
$instance = new C($args);
var instance = new C();
var instance = new C(args);
instance: new ClassName
instance: new ClassName "args"
ClassName instance = ClassName();

// in the stack, as opposed to the heap:
ClassName* instance = new ClassName();

Subclass checking

if instance.is_a?(ClassName)
if isinstance(instance, ClassName):
# Also, issubclass(ClassName, Parent)
if ($instance instanceof ClassName)
if (is_instance_of($instance, ClassName))

                

                

                

Getting the class

instance.class #=> ClassName
instance.__class__ #=> ClassName
__CLASS__ // from within
get_class($instance) #=> 'ClassName'
instance.constructor //=> ClassName

                
const std::type_info& info = typeid(instance);
info.name(); // const char*

Calling methods (from inside the class)

meth(args)
self.meth(args)
$this->meth(args);
this.meth(args);

                
meth(args);

Calling methods (elsewhere)

instance.meth
instance.meth(args)
instance.meth()
instance.meth(args)
$instance->meth(args);
instance.meth(args);

                
instance.meth(args);

MyClass* ptr = &instance;
ptr->meth(args);

Calling class methods

ClassName.meth
ClassName.meth(args)
ClassName.meth()
ClassName.meth(args)
ClassName::meth(args);
ClassName.meth(args);

                
ClassName::meth(args);

Calling a parent class method

def meth
super
end
class B(A):
def meth(self):
return super(A, self).meth()
function meth() {
return parent::meth();
}

                

                

                

Basics

Ruby Python PHP JavaScript CoffeeScript CPP

If-then-else

if x == y
# ...
elsif y == z and z == a
# ...
else
# ...
end

print "hi" if foo.nil?
print "hi" unless foo.empty?
if x == y:
# ...
elif y == z and z == a:
# ...
else:
# ...
if ($x == $y) {
// ...
} else if (($y == $z) && ($z == $a)) {
// ...
} else {
// ...
}
if (x == y) {
// ...
} else if ((y == z) && (z == a)) {
// ...
} else {
// ...
}
if x == y
# ...
else if y == z and z == a
# ...
else
# ...

alert "foo" if x == y
if (x == y) {
// ...
} else if ((y == z) && (z == a)) {
// ...
} else {
// ...
}

Switch


                

                

                

                
switch day
when "Mon" then goToWork()
when "Tue" then
goEat()
goSleep()
else conquerTheWorld()

                

Loops


                

                

                

                

                

                

Variables

Ruby Python PHP JavaScript CoffeeScript CPP

Local variables

myvar = 1
myvar
myvar = 1
myvar
$myvar = 1;
$myvar
var myvar = 1;
myvar

                
int myvar = 1;
myvar

Global variables

$gvar = 1

                
global $gvar;
$gvar = 1;
window.gvar = 1;

                

                

Instance variables

@var
# private
self.var
# public
class ClassName {
var $myvar;
}

$this->myvar
this.var

                
class ClassName {
public:
int myvar;
};

myvar;
this->myvar;

Class variables

@@var
# private
ClassName.var
# public
ClassName::$var
// Consider static vars instead
// ...

                
class ClassName {
public:
static int myvar;
};

myvar;
this->myvar;
ClassName::myvar;

Properties

Ruby Python PHP JavaScript CoffeeScript CPP

Getters

def attr
@attr
end

# or:
attr_reader :attr
def get_attr(self):
return self._attr
attr = property(get_attr)
public function __get($key) {
if ($key == 'attr')
{ return $this->attr; }
}

                

                

                

Setters

def attr=(val)
@attr = val
end

# or:
attr_writer :attr
def set_attr(self, val):
self._attr = val
attr = property(None, set_attr)
public function __set($key, $val) {
if ($key == 'attr')
{ $this->attr = $val; }
}

                

                

                

Getters and setters

# Defines `attr` and `attr=`
attr_accessor :attr
property(get_attr, set_attr)
# Also:
# property(getter, setter, deleter, doc)

                

                

                

                

Getting a property with an arbitrary name

obj.send :attr
obj.send :'attr=', value
getattr(obj, 'attr')
setattr(obj, 'attr', value)
$obj->{'attr'}
$obj->{'attr'} = $value;
obj['attr'] // same as obj.attr

                

                

Constants

Ruby Python PHP JavaScript CoffeeScript CPP

Common constants

true
false
nil
True
False
None
TRUE
FALSE
NULL
true
false
null
undefined
NaN
Infinity

                
true
false
NULL /* void* NULL = 0; */

Methods and Functions

Ruby Python PHP JavaScript CoffeeScript CPP

Declaring methods

def meth(args)
# ...
end
def meth(self, args):
# ...
function meth(args) {
// ...
}
// Many many ways
Class.prototype.meth = function(args) {
// ...
}

                
// file.h
class MyClass {
public:
int mymethod(void* args);
};

// file.cpp
int MyClass::mymethod(void *args) {}

Constructor

def initialize
def __init__(self):
public function __construct() {}
// ...

                
class MyClass {
MyClass() { /* ... */ }
MyClass() : initializers { /* ... */ }
}

Static methods

def self.meth
@classmethod
def meth(cls):
public static function meth() {}
Class.meth = function(args) {}

                

                

Running a method with an arbitrary name

obj.send :method_name, arg1, arg2
# obj.__send__ is also available
getattr(obj, 'method_name')(arg1, arg2)
$obj->{'method_name'}(arg1, arg2);
obj['method_name'](arg1, arg2);

                

                

Anonymous functions

Ruby Python PHP JavaScript CoffeeScript CPP

Anonymous functions

fn = lambda { |x| x+1 }
fn = -> { |x| x+1 } # Ruby 1.9
fn.call(4) #=> 5
fn = lambda x: x+1
fn(4) #=> 5
$fn = create_function('$x', 'return $x+1;');
$fn = function($x) { return $x+1; }; // 5.3
$fn(4); //=> 5
var fn = function(x) { return x+1; }
fn(4); //=> 5

                

                

Namespaces

Ruby Python PHP JavaScript CoffeeScript CPP

Namespaces

# foo.rb
module Foo
class Bar
# ...
end
end

# elsewhere:
$fb = Foo::Bar.new
# foo.py
class Bar:
pass

# elsewhere:
import foo
fb = foo.Bar()

# or:
from foo import Bar
fb = Bar()
// Namespaces are only for PHP 5.3+
// foo.php
namespace Foo;
class Bar { /* ... */ }

// elsewhere:
$fb = new Foo\Bar();
Foo = {
Bar: function() { /* ... */ }
};

// elsewhere:
var fb = new Foo.Bar();

                
namespace Foo {
class Bar { /* ... */ };
}

// elsewhere:
Foo::Bar instance;

using namespace Foo;
Bar instance;

String representation

Ruby Python PHP JavaScript CoffeeScript CPP

Getting string representations

obj.to_s
obj.inspect
str(obj)
repr(obj) # Attempts to make
# eval()'able output
print_r($obj)
var_export($obj) // eval()able
obj.toString()
String(obj)

                

                

Overriding string representations

def to_s
def inspect
def __str__(self):
def __repr__(self):
public function __toString() {}

                

                

                

Types

Ruby Python PHP JavaScript CoffeeScript CPP

Type classes

Fixnum
Bignum
String
Integer
Time
RegExp
Symbol
int
bool
str
unicode

                
Number
Array
Boolean
Date
String
RegExp

                
void
int /* unsigned, long, short */
bool
std::string

int[] /* array */
int* /* pointer */

Type checking

if obj.is_a? Fixnum
if isinstance(obj, str):
is_bool($obj)
is_int($obj)
is_scalar($obj) // integer, float,
// string, or boolean

// Also: is_float(), is_int(), is_numeric(),
// is_string(), is_bool(), is_object(),
// is_array()
if (typeof obj == "string") {}
// also: object, function, array

                
void* ptr =
dynamic_cast<ClassName*>(instance_ptr);
if (ptr) { /* success */ }

Casting

obj.to_s
obj.to_i
obj.to_f
str(obj)
int(obj)
float(obj)
bool(obj)
(string) $obj
(int) $obj
(float) $obj
(bool) $obj
parseInt($obj)
parseFloat($obj)
String($obj)
Number($obj)

                
// Basic casting
void* ptr = &obj;
*((int*) ptr);

dynamic_cast<ClassName*> (&obj);
static_cast<ClassName*> (&obj);
reinterpret_cast<ClassName*> (&obj);
const_cast<ClassName*> (&obj);

Arrays

Ruby Python PHP JavaScript CoffeeScript CPP

Initializing (empty)

arr = Array.new
arr = list()
$arr = array();
var arr = [];

                
int arr[] = [];

#include <vector>
std::vector<int> vect;

Initializing (with contents)

arr = [1, 2, 3]
# %w[red green]
arr = [1, 2, 3]
$arr = array(1, 2, 3);
var arr = [1, 2, 3];

                
int arr[] = [1, 2, 3];

Accessing items

arr[0]
arr[0]
$arr[0]
arr[0]

                
vect[0]

Length

arr.size #=> 3
arr.empty?
arr.any?
len(arr) #=> 3
count(arr) //=> 3
arr.length //=> 3

                
vect.size()

Adding items

arr << 4        #=>   [1,2,3,4]
arr.unshift(0) #=> [0,1,2,3,4]
arr.append(4)      #=>   [1,2,3,4]
arr.insert(0, 'X') #=> [X,1,2,3,4]
$arr[]= 4;               //=>   [1,2,3,4]
array_push($arr, 4); // same as above
array_unshift($arr, 0); //=> [0,1,2,3,4]
arr.push(4);    //=> [1,2,3,4]
arr.unshift(0); //=> [0,1,2,3,4]

                

                

Removing items

arr.pop   #=> 4
arr #=> [0,1,2,3]
arr.shift #=> 0
arr #=> [1,2,3]
arr.pop()   #=> 4
arr #=> [0,1,2,3]
arr.shift() #=> 0
arr #=> [1,2,3]
array_pop($arr);   //=> 4
$arr; //=> [0,1,2,3]
array_shift($arr); //=> 0
$arr; //=> [1,2,3]
arr.pop();    //=> 4
arr; //=> [0,1,2,3]
arr.shift(); //=> 0
arr; //=> [1,2,3]

                

                

Checking for presence of items

if [1, 2, 3].include?(2)
if 2 in [1, 2, 3]:
if (in_array(2, array(1, 2, 3))) {}
if ([1, 2, 3].indexOf(2) != -1) {}

                

                

Searching

# .detect
# .empty? .any?

                

                

                

                

                

Sorting


                

                

                

                

                

                

Hash tables

Ruby Python PHP JavaScript CoffeeScript CPP

Initializing empty hashes

hash = Hash.new()
mydict = dict()
$hash = array();
var hash = {};

                
#include <map>
std::map<Key,T> map;

Initializing with contents

hash = { :red => 1, :green => 2 }
hash = { red: 1, green: 2 } # Ruby 1.9
hash = Hash.new([[:red, 1], [:green, 2]])
mydict = { 'red': 1, 'green': 2 }
mydict = dict([['red', 1], ['green', 2]])
mydict = dict(red=1, green=2)
$arr = array( 'red' => 1, 'green' => 2 );
var arr = { 'red': 1, 'green': 2 };

                

                

Iterating hashes

hash.each do |key, val|
for key, val in mydict.iteritems():
foreach ($arr as $key => $val) {}
// Also array_walk()
for (key in arr) {
var value = arr[key];

                

                

Keys

hash.keys
mydict.keys()
for key in mydict.iterkeys():
array_keys($arr)
for (key in arr) {}

                

                

Iteratables

Ruby Python PHP JavaScript CoffeeScript CPP

Iterating

mylist.each do |item|
for item in mylist:
foreach ($mylist as $item) {}
// Also array_walk()
for (i in mylist) {
var item = mylist[i];

                
std::vector<int> vect;
std::vector<int>::iterator it;
for (it = vect.begin(); it != vect.end(); it++) {
}

Map

mylist.map do |item|
expr(item)
end
map(lambda item: expr(item), mylist)
# or:
[expr(item) for item in mylist]
# also: [expr for i in mylist if cond]
array_map($mylist, 'callback')
// underscore.js
_.map(mylist, function(item) {
// ...
})

                

                

Inject

mylist.inject do |acc, item|
acc + item; acc
end
reduce(
lambda acc, item: acc + item,
mylist)

                
// underscore.js
_.inject(mylist, function(acc, item) {
// ...
})

                

                

Printing

Ruby Python PHP JavaScript CoffeeScript CPP

Printing

puts "hello"
p "hello"
print "hello"
echo "hello";
print "hello";
document.writeln("hello");

                
std::cout << "Hello";

Error output

$stderr << "Error\n"
sys.stderr.write("Error\n")
fwrite(STDERR, "Error\n");
console.log("Error");

                
std::cerr << "Error" << std::endl;

Strings

Ruby Python PHP JavaScript CoffeeScript CPP

Interpolation

"Hi #{name}"
'Hi %s' % name
'Hi %{name}' % {name: name}
'Hi %s' % name
'Hi %{name}' % {name: name}
"Hi $name"
"Hi {$name}"
sprintf('Hi %s', $name)

                

                

                

Concatenation

"a" + "b"
"a" + "b"
"a" . "b"
"a" + "b"

                
std::string mystring;
mystring + mystring2;

char str[80];
strcpy(str, "a");
strcat(str, "b");

Uppercase/lowercase

"Hey".downcase
"Hey".upcase
"Hey".upper()
"Hey".lower()
"hey you".title() #=> 'Hey You'
"hey you".capitalize() #=> 'Hey you'
"Hey you".swapcase()
strtolower("Hey")
strtoupper("Hey")
"Hey".toUpperCase()
"Hey".toLowerCase()

                

                

String length

"Hello".size
len("Hello")
strlen("Hello")
"Hello".length

                

                

Substring

str = "Hello world"
str[1...5] #=> 'ello'
str[-5..-1] #=> 'world'
str[0...-4] #=> 'Hello w'
str = "Hello world"
str[1:5] #=> 'ello'
str[-5:] #=> 'world'
str[0:-4] #=> 'Hello w'
$str = "Hello world";
substr($str, 1, 4) //=> 'ello'
substr($str, -5) //=> 'world'
substr($str, 0, -4) //=> 'Hello w'
str = "Hello world";
substr(str, 1, 4) //=> 'ello'
substr(str, -5) //=> 'world'
substr(str, 0, str.length-4)
// str.substr(n, n) also works

                

                

Replacing

'Hi'.gsub('i', 'ey')
'Hi'.replace('i', 'ey')
str_replace('Hi', 'i', 'ey')
'Hi'.replace('i', 'ey')

                

                

Finding

'Hi'.include?('i')  #=> true
'i' in 'Hi'     #=> true
'Hi'.find('i') #=> 1
'Hi'.find('o') #=> -1
strchr()
strpos('Hi', 'i') //=> 1
strpos('Hi', 'o') //=> -1
'Hi'.indexOf('i')  //=> 1
'Hi'.indexOf('o') //=> -1

                

                

Numbers

Ruby Python PHP JavaScript CoffeeScript CPP

Rounding off

(2.5).to_i    #=> 2
(2.5).floor #=> 2
(2.5).ceil #=> 3
(2.5).round #=> 3
math.trunc(2.5)    #=> 2
math.floor(2.5) #=> 2
math.ceil(2.5) #=> 3
round(2.5) #=> 3
round(3.14159, 2) #=> 3.14
(int) 2.5          //=> 2
floor(2.5) //=> 2
ceil(2.5) //=> 3
round(2.5) //=> 3
round(3.14159, 2) //=> 3.14
parseInt(2.5)      //=> 2
Math.floor(2.5) //=> 2
Math.ceil(2.5) //=> 3
Math.round(2.5) //=> 3
(3.141).toFixed(2) //=> 3.14

                

                

Minimum and maximum

[2, 4].min  #=> 2
[2, 4].max #=> 4
min(2, 4)   #=> 2
max(2, 4) #=> 4
min([2, 4])
min(2, 4)   //=> 2
max(2, 4) //=> 4
min(array(2, 4))
Math.min(2, 4)   //=> 2
Math.max(2, 4) //=> 4

                

                

Exponents

2**8 #=> 256
import math
math.pow(2, 8) #=> 256
pow(2, 8) //=> 256
Math.pow(2, 8) //=> 256

                

                

Trigonometry

# Radians assumed
Math.sin(theta)
Math::PI #=> 3.14159...
# Radians assumed
import math
math.sin(theta)
math.pi #=> 3.14159...
// Radians assumed
sin(theta)
sin(deg2rad(angle))
pi() // or M_PI => 3.14159...
Math.sin(theta)
Math.PI //=> 3.14159...

                

                

Exceptions

Ruby Python PHP JavaScript CoffeeScript CPP

Exception throwing

raise StandardError
raise NameError('Hello')
throw new Exception('Hello');
throw new Exception('Hello');

                
void my_function() throw() {
Exception e();
throw e;
}

Exception handling

begin
# do things
rescue StandardError => e
# handle the exception
retry
ensure
# ...
end

# Also:
rescue => e
rescue StandardError
try:
# do things
except NameError as e:
# handle the exception
else:
# ...
finally:
# ...

# Also:
except NameError:
try {
// do things
} catch (Exception $e) {
// handle the exception
}
try {
// do things
}
catch (Exception e) {
// handle the exception
}

                
try {
// do things
my_function();
}
catch (Exception& e) {
// handle the exception
}

Overriding

Ruby Python PHP JavaScript CoffeeScript CPP

Overriding instance[i]

def [](i)
def []=(i, value)
def __getitem__(self, i):
def __setitem__(self, i, value):
def __delitem__(self, i):

# To override instance[i:j]:
def __getslice__(self, i, j):
def __setslice__(self, i, j):
def __delslice__(self, i, j):

                

                

                

                

Catching a missing attrib/method

def method_missing(meth, *args)
def __getattr__(self, attr):
public function __get($attr) {}
public function __set($attr, $v) {}
public function __call($meth, $args) {}

                

                

                

Overriding ClassName()


                

                
public function __invoke() {}

                

                

                

Overloading operators

def <<(other)
def +(other) # also * / - < ...
def -@ # unary -, also +@
def <=>(other) # include Comparable
def __add__(self, other):
def __sub__(self, other):
def __mul__(self, other):
def __pow__(self, other[, modulo]):
def __cmp__(self, other):
# Also: floordiv, mod, divmod, pow, lshift,
# rshift, and, xor, or, div, ...

                

                

                

                

Files

Ruby Python PHP JavaScript CoffeeScript CPP

Path joining

File.join('dir', 'file')
os.path.join('dir', 'file')
'dir' . DIRECTORY_SEPARATOR . 'file'
var path = require('path'); // NodeJS only
path.join('dir', 'file');

                

                

Getting path info

fpath = 'dir/sub/file.txt'
File.dirname(fpath) #=> 'dir/sub'
File.basename(fpath) #=> 'file.txt'

File.basename(fpath, '.txt') #=> 'file'
File.basename(fpath, '.*') #=> 'file'
File.extname(fpath) #=> '.txt'
fpath = 'dir/sub/file.txt'
os.path.dirname(fpath) #=> 'dir/sub'
os.path.basename(fpath) #=> 'file.txt'

os.path.split(fpath)
#=> ['dir/sub', 'file.txt']
$fpath = 'dir/sub/file.txt';
dirname($fpath); //=> 'dir/sub'
basename($fpath); //=> 'file.txt'
// NodeJS
fpath = 'dir/sub/file.txt';

path.dirname(fpath); //=> 'dir/sub'
path.basename(fpath); //=> 'file.txt'

ptah.basename(fpath, '.txt') //=> 'file'
ptah.basename(fpath, '.*') //=> 'file'
ptah.extname(fpath) //=> '.txt'

                

                

Getting current directory

Dir.pwd
File.dirname(__FILE__)
os.getcwd()
getcwd()
dirname(__FILE__)

                

                

                

File existence check

if File.exists?(fname)
if os.path.isfile(fname):
if (is_file($fname)) {}
// NodeJS async
path.exists('/etc/passwd', function(exists) {
console.log(exists ? 'yes' : 'no');
});

// NodeJS synchronous
var exists = path.existsSync('/etc/passwd');
console.log(exists ? 'yes' : 'no');

                

                

Is directory check

File.directory?(dname)
if os.path.isdir(dname):
if (is_dir(dname)) {}

                

                

                

Quick reading

data = File.open('f.txt') { |f| f.read }
with open('f.txt', 'r') as f:
data = f.read()
$data = file_get_contents('f.txt');

                

                

                

Quick writing

File.open('f.txt', 'w') { |f| f << data }
with open('f.txt', 'w') as f:
f.write(data)
file_put_contents('f.txt', $data);

                

                

                

DOM Manipulation

Ruby Python PHP JavaScript CoffeeScript CPP

DOM manipulation


                

                

                
createNode(type, name);

// JQuery:
$("<div>");

                

                

DOM traversion


                

                

                
node.parentNode();
node.childNodes();
node.firstChild();
node.nextSibling();
node.prevSibling();

// JQuery:
$node.parents("form");
$node.find(">*");

                

                

Other notes

Ruby Python PHP JavaScript CoffeeScript CPP

Installing


                

                

                

                
# http://jashkenas.github.com/coffee-script/
sudo bin/cake install
brew install coffeescript # with OSX/Homebrew
npm install -g coffee-script # with NPM

                

Running

ruby file.rb
irb # REPL shell
python file.py
python # REPL shell
php file.php
php -a # REPL shell

                
coffee -c path/to/script.coffee
coffee --interactive # REPL shell
coffee --watch --lint script.coffee
coffee --print js/*.coffee > all.js
# Assuming GNU C++
gcc foo.cpp -o foo.o
ld -o foo foo.o
./foo