|
Source Layout
|
|
|
|
|
|
Ruby is a line-oriented language.
You can also put a backslash at the end
of a line to continue it onto the next.
|
|
Comments
|
// comments
/* comments */
|
# comments
/* comments */
|
# comments
/* comments */
|
// comments
/* comments */
|
// comments
/* comments */
|
# this is a comment line
=begin
everything between a line beginning with `=begin' down to
one beginning with `=end' will be skipped by the interpreter.
=end
|
|
String
|
"abc"
|
'this is a simple string'
"abc"
<<<EOD
Example of string spanning multiple lines
using heredoc syntax.
EOD
|
'this is a simple string'
"abc"
<<<EOD
Example of string spanning multiple lines
using heredoc syntax.
EOD
|
"abc"
'abc'
|
var str = new String("Hello world!");
var str1 = "Hello world!";
|
abc"'" |
|
Declaring Variables
|
int x;
int x = 10;
|
n/a
|
n/a
|
int x;
int x = 10;
|
var x = "I am string";
var y = 100;
|
# A variable whose name begins with a lowercase letter (a-z) or
# underscore (_) is a local variable
foobar
#A variable whose name begins with '@' is an instance variable of self
@foobar
#A variable whose name begins with '@' is an class variable
@@foobar
#A variable whose name begins with '$' has a global scope
$foobar
#A variable whose name begins with an uppercase letter (A-Z) is a constant.
FOOBAR
|
|
Variable parsing
|
n/a
|
$beer = 'Heineken';
echo "$beer's taste is great";
echo "He drank some ${beer}s";
echo "He drank some {$beer}s";
|
$beer='Heineken';
echo "$beer's taste is great;";
echo "He drank some ${beer}s";
echo "He drank some {$beer}s";
|
n/a
|
n/a
|
n/a
|
|
Assignment Statements
|
nVal = 7;
|
$a = 5;
$a += $a = 5;
$a += 2;
$b = "a";
$b .= "b";
|
|
|
var a = "I am string";
var b = a;
|
a = b = 1 + 2 + 3
# Parallel Assignment
a, b = b, a
a = [1, 2, 3, 4]
b, c = a # b == 1, c == 2
b, *c = a # b == 1, c == [2, 3, 4]
# Nested Assignments
b, (c, d), e = 1,2,3,4 # b == 1, c == 2, d == nil, e == 3
|
|
Conditional Statements
|
if (nCnt <=if (nCnt <= nMax){
nTotal += nCnt;
nCnt++;
} else {
nTotal +=nCnt;
nCnt--;
}
|
if ($a > $b) {
echo "a is bigger than b";
} else {
echo "a is NOT bigger than b";
}
|
if (nCnt <= n){
} else {
}
|
|
if(a > b){
// code.. }
|
if count > 10
puts "Try again"
elsif tries == 3
puts "You lose"
else
puts "Enter a number"
end
a = 7 unless a == 4
|
|
Selection Statements
|
switch(n) {
case 0:
Console.WriteLine("Zero");
break;
case 1:
Console.WriteLine("One");
break;;
default:
Console.WriteLine("?");
break;
}
|
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
default:
echo "i is not equal to 0, 1 or
2";
}
|
|
switch(n) {
case 0:
trace("Zero");
break;
case 1:
trace("One");
break;;
default:
trace("?");
break;
}
|
switch(n) {
case 0:
document.write("Zero");
break;
case 1:
document.write("One");
break;;
default:
document.write("?");
break;
}
|
leap = case
when year % 400 == 0: true
when year % 100 == 0: false
else year % 4 == 0
end
case input_line
when "debug"
dump_symbols
when /p\s+(\w+)/
dump_variable($1)
when "quit", "exit"
exit
else
print "Illegal command: #{input_line}"
end
case year
when 1850..1889 then "Blues"
when 1890..1909 then "Ragtime"
when 1910..1929 then "New Orleans Jazz"
when 1930..1939 then "Swing"
when 1940..1950 then "Bebop"
else "Jazz"
end
|
|
For Loops
|
// for loop
for (int i = 1; i <= 10; i++) {
Console.WriteLine(
"The number is {0}",
i);
}
// foreach loop
foreach (int i in testArr) {
Console.WriteLine(i);
}
|
// for loop
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
// foreach loop
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
|
// Array with key and value
class MyClass{
public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';
protected $protected = 'protected var';
private $private = 'private var';
function iterateVisible() {
echo
"MyClass::iterateVisible:\n";
foreach($this as $key=>$value)
{
print "$key
=>";
}
}
}
$class = new MyClass();
foreach($class as $key =>$value) {
print "$key =>$value\n";
}
echo "\n";
$class->iterateVisible();
|
// for loop
for (int i = 1; i <= 10; i++) {
trace(i)
}
// foreach loop
for each (var n:int in obj) {
trace(n + "=" + obj[n]);
}
|
for (int i = 1; i <= 10; i++) {
document.write(
"The number is" + i+"
");
}
|
3.times do
print "Ho! "
end
0.upto(9) do |x|
print x, " "
end
for song in songlist
song.play
end
|
|
While Loops
|
while (n < 100)
n++;
|
/* example 1 */
$i = 1;
while ($i <= 10) {
echo $i++;
/* the printed value would be
$i before the increment
(post-increment) */
}
/* example 2 */
$i = 1;
while ($i <= 10):
print $i;
$i++;
endwhile;
|
|
while (n < 100)
n++;
|
while (n < 100)
n++;
|
while line = file.gets
puts(line) if line =~ /third/ .. line =~ /fifth/
end
until play_list.duration > 60
play_list.add(song_list.pop)
end
a *= 2 while a < 100
|
|
Parameter Passing by Value
|
// Calling the method:ABC(i);
void ABC(int x){ ...}
|
function takes_array($input) {
echo "$input[0] + $input[1] = "
, $input[0]+$input[1];
}
|
|
|
function functionName([argname1 [, ...[, argnameN]]]){
//body
}
|
|
|
Parameter Passing by Reference
|
// Calling the method:ABC(ref i);
void ABC(ref int x){ ...}
|
function add_some_extra(&$string){
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;
// outputs 'This is a string,
// and something extra.'
|
|
|
|
|
|
Structured Exception Handling Reference
|
try{
if (x == 0)
throw new Exception ("x equals zero");
else {
throw new Exception(
"x does not equal zero");
}
}
catch (Exception err){
Console.WriteLine(err.Message);
}
finally{
Console.WriteLine(
"executing finally block");
}
|
try {
$error = 'Always throw this error';
throw new Exception($error);
echo 'Never executed';
}
catch (Exception $e) {
echo 'Caught exception: ',
$e->getMessage(),"\n";
}
// continue
echo 'Hello World';
|
|
try{
{ }
catch (err:String){
}
finally{
}
|
function initException(Num,Msg)//define an Exception
{
this.ErrorNumber=Num;//error's number
this.ErrorMessage=Msg;//error's message
}
function CreateException()
{
//create the excepion
ex=new initException(1,"Created!");
throw ex;//throw ex
}
function test()
{
try
{
CreateException();
}
catch(ex)//catch the ex
{
//if the exception is our target,do something
if(ex instanceof initException)
{
alert(ex.ErrorNumber+ex.ErrorMessage);
}
else//else throw again
{
throw ex;
}
}
finally
{
alert("end");//do something finally
}
}
|
begin
eval string
rescue SyntaxError, NameError => boom
print "String doesn't compile: " + boom
rescue StandardError => bang
print "Error running script: " + bang
end
|
|
Set an Object Reference to Nothing
|
o = null;
|
$var = NULL;
unset($foo);
|
|
abc = undefined;
|
var obj = null;
|
o = nil
|
|
Closure
|
|
|
|
|
function Person(firstName, lastName, age){
//private variables
var _firstName = firstName;
var _lastName = lastName;
//public variables
this.age = age;
//Methods£º
this.getName = function(){
return(firstName + " " + lastName);
};
this.SayHello = function(){
alert("Hello, I'm " + firstName + " " + lastName);
};
};
var BillGates = new Person("Bill", "Gates", 53);
var SteveJobs = new Person("Steve", "Jobs", 53);
BillGates.SayHello();
SteveJobs.SayHello();
alert(BillGates.getName() + " " + BillGates.age);
//alert(BillGates.firstName);
//cannot access the private variable.
|
def highPaid(emps)
threshold = 150
return emps.select {|e| e.salary > threshold}
end
|
|
Prototype
|
|
|
|
|
//Declare Constructor
function Person(name){
this.name = name; //Declare filed in Contructor
};
//Add method in the prototype
Person.prototype.SayHello = function(){
alert("Hello, I'm " + this.name);
};
//Constructor of subclass
function Employee(name, salary){
Person.call(this, name); //Call Person Constructor
this.salary = salary; //Add salary field.
};
//Subclass constructor function should call the
//base class constructor to create the prototype object.
Employee.prototype = new Person();
//Subclass method is defined
Employee.prototype.ShowMeTheMoney = function(){
alert(this.name + " $" + this.salary);
};
var BillGates = new Person("Bill Gates");
BillGates.SayHello();
var SteveJobs = new Employee("Steve Jobs", 1234);
SteveJobs.SayHello();
SteveJobs.ShowMeTheMoney();
|
|