Notes |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
// C++ is only here to serve as a comparison
|
Classes |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Class |
class ClassName
|
class ClassName:
|
class ClassName {
|
// Many ways; this one's used often:
|
class ClassName
|
class ClassName {
|
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,
|
||||
Instantiation |
instance = C.new
|
instance = C()
|
$instance = new C();
|
var instance = new C();
|
instance: new ClassName
|
ClassName instance = ClassName();
|
Subclass checking |
if instance.is_a?(ClassName)
|
if isinstance(instance, ClassName):
|
if ($instance instanceof ClassName)
|
|||
Getting the class |
instance.class #=> ClassName
|
instance.__class__ #=> ClassName
|
__CLASS__ // from within
|
instance.constructor //=> ClassName
|
const std::type_info& info = typeid(instance);
|
|
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()
|
$instance->meth(args);
|
instance.meth(args);
|
instance.meth(args);
|
|
Calling class methods |
ClassName.meth
|
ClassName.meth()
|
ClassName::meth(args);
|
ClassName.meth(args);
|
ClassName::meth(args);
|
|
Calling a parent class method |
def meth
|
class B(A):
|
function meth() {
|
Basics |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
If-then-else |
if x == y
|
if x == y:
|
if ($x == $y) {
|
if (x == y) {
|
if x == y
|
if (x == y) {
|
Switch |
switch day
|
|||||
Loops |
Variables |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Local variables |
myvar = 1
|
myvar = 1
|
$myvar = 1;
|
var myvar = 1;
|
int myvar = 1;
|
|
Global variables |
$gvar = 1
|
global $gvar;
|
window.gvar = 1;
|
|||
Instance variables |
@var
|
self.var
|
class ClassName {
|
this.var
|
class ClassName {
|
|
Class variables |
@@var
|
ClassName.var
|
ClassName::$var
|
// ...
|
class ClassName {
|
Properties |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Getters |
def attr
|
def get_attr(self):
|
public function __get($key) {
|
|||
Setters |
def attr=(val)
|
def set_attr(self, val):
|
public function __set($key, $val) {
|
|||
Getters and setters |
# Defines `attr` and `attr=`
|
property(get_attr, set_attr)
|
||||
Getting a property with an arbitrary name |
obj.send :attr
|
getattr(obj, 'attr')
|
$obj->{'attr'}
|
obj['attr'] // same as obj.attr
|
Constants |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Common constants |
true
|
True
|
TRUE
|
true
|
true
|
Methods and Functions |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Declaring methods |
def meth(args)
|
def meth(self, args):
|
function meth(args) {
|
// Many many ways
|
// file.h
|
|
Constructor |
def initialize
|
def __init__(self):
|
public function __construct() {}
|
// ...
|
class MyClass {
|
|
Static methods |
def self.meth
|
@classmethod
|
public static function meth() {}
|
Class.meth = function(args) {}
|
||
Running a method with an arbitrary name |
obj.send :method_name, arg1, arg2
|
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 = lambda x: x+1
|
$fn = create_function('$x', 'return $x+1;');
|
var fn = function(x) { return x+1; }
|
Namespaces |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Namespaces |
# foo.rb
|
# foo.py
|
// Namespaces are only for PHP 5.3+
|
Foo = {
|
namespace Foo {
|
String representation |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Getting string representations |
obj.to_s
|
str(obj)
|
print_r($obj)
|
obj.toString()
|
||
Overriding string representations |
def to_s
|
def __str__(self):
|
public function __toString() {}
|
Types |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Type classes |
Fixnum
|
int
|
Number
|
void
|
||
Type checking |
if obj.is_a? Fixnum
|
if isinstance(obj, str):
|
is_bool($obj)
|
if (typeof obj == "string") {}
|
void* ptr =
|
|
Casting |
obj.to_s
|
str(obj)
|
(string) $obj
|
parseInt($obj)
|
// Basic casting
|
Arrays |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Initializing (empty) |
arr = Array.new
|
arr = list()
|
$arr = array();
|
var arr = [];
|
int arr[] = [];
|
|
Initializing (with contents) |
arr = [1, 2, 3]
|
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
|
len(arr) #=> 3
|
count(arr) //=> 3
|
arr.length //=> 3
|
vect.size()
|
|
Adding items |
arr << 4 #=> [1,2,3,4]
|
arr.append(4) #=> [1,2,3,4]
|
$arr[]= 4; //=> [1,2,3,4]
|
arr.push(4); //=> [1,2,3,4]
|
||
Removing items |
arr.pop #=> 4
|
arr.pop() #=> 4
|
array_pop($arr); //=> 4
|
arr.pop(); //=> 4
|
||
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
|
|||||
Sorting |
Hash tables |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Initializing empty hashes |
hash = Hash.new()
|
mydict = dict()
|
$hash = array();
|
var hash = {};
|
#include <map>
|
|
Initializing with contents |
hash = { :red => 1, :green => 2 }
|
mydict = { '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) {}
|
for (key in arr) {
|
||
Keys |
hash.keys
|
mydict.keys()
|
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) {}
|
for (i in mylist) {
|
std::vector<int> vect;
|
|
Map |
mylist.map do |item|
|
map(lambda item: expr(item), mylist)
|
array_map($mylist, 'callback')
|
// underscore.js
|
||
Inject |
mylist.inject do |acc, item|
|
reduce(
|
// underscore.js
|
Printing |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Printing |
puts "hello"
|
print "hello"
|
echo "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"
|
|||
Concatenation |
"a" + "b"
|
"a" + "b"
|
"a" . "b"
|
"a" + "b"
|
std::string mystring;
|
|
Uppercase/lowercase |
"Hey".downcase
|
"Hey".upper()
|
strtolower("Hey")
|
"Hey".toUpperCase()
|
||
String length |
"Hello".size
|
len("Hello")
|
strlen("Hello")
|
"Hello".length
|
||
Substring |
str = "Hello world"
|
str = "Hello world"
|
$str = "Hello world";
|
str = "Hello world";
|
||
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
|
strchr()
|
'Hi'.indexOf('i') //=> 1
|
Numbers |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Rounding off |
(2.5).to_i #=> 2
|
math.trunc(2.5) #=> 2
|
(int) 2.5 //=> 2
|
parseInt(2.5) //=> 2
|
||
Minimum and maximum |
[2, 4].min #=> 2
|
min(2, 4) #=> 2
|
min(2, 4) //=> 2
|
Math.min(2, 4) //=> 2
|
||
Exponents |
2**8 #=> 256
|
import math
|
pow(2, 8) //=> 256
|
Math.pow(2, 8) //=> 256
|
||
Trigonometry |
# Radians assumed
|
# Radians assumed
|
// Radians assumed
|
Math.sin(theta)
|
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 handling |
begin
|
try:
|
try {
|
try {
|
try {
|
Overriding |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Overriding instance[i] |
def [](i)
|
def __getitem__(self, i):
|
||||
Catching a missing attrib/method |
def method_missing(meth, *args)
|
def __getattr__(self, attr):
|
public function __get($attr) {}
|
|||
Overriding ClassName() |
public function __invoke() {}
|
|||||
Overloading operators |
def <<(other)
|
def __add__(self, other):
|
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
|
||
Getting path info |
fpath = 'dir/sub/file.txt'
|
fpath = 'dir/sub/file.txt'
|
$fpath = 'dir/sub/file.txt';
|
// NodeJS
|
||
Getting current directory |
Dir.pwd
|
os.getcwd()
|
getcwd()
|
|||
File existence check |
if File.exists?(fname)
|
if os.path.isfile(fname):
|
if (is_file($fname)) {}
|
// NodeJS async
|
||
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 = file_get_contents('f.txt');
|
|||
Quick writing |
File.open('f.txt', 'w') { |f| f << data }
|
with open('f.txt', 'w') as f:
|
file_put_contents('f.txt', $data);
|
DOM Manipulation |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
DOM manipulation |
createNode(type, name);
|
|||||
DOM traversion |
node.parentNode();
|
Other notes |
Ruby | Python | PHP | JavaScript | CoffeeScript | CPP |
|---|---|---|---|---|---|---|
Installing |
# http://jashkenas.github.com/coffee-script/
|
|||||
Running |
ruby file.rb
|
python file.py
|
php file.php
|
coffee -c path/to/script.coffee
|
# Assuming GNU C++
|