- Line endings separate statements. Semicolons optional.
- Line comments begin with
# - Block comments enclosed by
=beginand=end
- Arithmetical:
+,-,*,/,%,**(exponent) - Comparison:
==,!=,>,>=,<,<=,<=>,===- Equality checking methods:
eq?(same value and type),equal?(same reference)
- Equality checking methods:
- Bitwise:
&(and),|(or),^(xor),~(not),<<,>> - Logical:
and,or,notor&&,||,!
There are also compound assignment counterparts for all arithmetical (e.g.
+=), all bitwise (e.g.&=) and some logical operators (&&=,||=).
All the above operators are methods and can thus be overloaded/overriden
defined?: Checks if a symbol is definedundefcancels a symbol definitionaliasdefines another global reference for the same symbol
| Variable Type | Scope | Syntax |
|---|---|---|
| Constants | begin with an uppercase letter | |
| Local Variables | function, method | begin with a lowercase letter or _ |
| Instance variables | object | begin with @ |
| Class Variables | class (static) | begin with @@ |
| Global Variables | process | begin with $ |
- Reserved variables:
self,true,false,nil,__FILE__,__LINE__
- The only falsey value in Ruby is
nil. Everything else is truthy, including the numeric0.
- String interpolation:
"#{foo} is a #{bar}".- Expressions in
#{...}are eval'ed - String interpolation allowed in heredocs.
- Expressions in
- Heredocs (starting with
<<) supported for defining long strings. - String Concatenation: the
<<operator appends to the string on the left, e.g."append" == "app" << "end"
- Array literals are enclosed in square brackets. e.g.
[ "an array with", 3, "elements", ]- Mixed type
- Trailing commas are ignored
- Arrays are integer indexed. Index starts at
0.- Negative indexes are relative to the end of the array,
-1indicating the last element
- Negative indexes are relative to the end of the array,
- Arrays can be initialized with a constructor:
Array.new(length, default_value)- the constructor can also use a block to initialize values:
nums = Array.new(10) { |e| do_something_with e }
- the constructor can also use a block to initialize values:
- Also supported: casting a range to an array
nums = Array(0..9) - Methods
sizeandlengthreturn the array length
| Between arrays | Between array and scalar |
|---|---|
a + b concatenation |
a * x self-concatenation x times |
a & b intersection (and) |
a * str implode with str as glue |
a | b union (or) |
a << x push x at the end |
a - b difference |
|
a == b equality |
- Hash literals are enclosed in curly brackers, e.g.
{ 'key1' => 'val1', 'key2' => 'val2' } - Object notation is supported for hash literals since Ruby 1.9, e.g.
{ key1: 'val1', key2: 'val2' }is equivalent to{ :key1 => 'val1', :key2 => 'val2' }
- Ranges express a sequence, e.g.
(1..10),('a'..'z') - Ranges can be closed (
(1..5)==> 1,2,3,4,5) or open ((1...5)==> 1,2,3,4) - Uses of ranges:
- as iterables:
(1..10).each - as conditions:
case x when (1..10) then ... - as intervals:
if (1..10) === x do ...,
- as iterables:
Arrays, Hashes and Ranges are examples of collections, i.e. enumerable objects with methods such as
eachandcollect.
if conditional # ... elsif conditional # ... else # ... end |
unless conditional # ... else # ... end |
case expression when expression, expression # ... else # ... end |
ifandunlesscan also be used as modifiers, e.g.x = a / b unless b == 0
while conditional do # ... end or begin # ... end while conditional or statement while condition |
until conditional do # ... end or begin # ... end until conditional or statement until condition |
for var in collection do # ... var is visible here ... end |
collection.each do |var| # ... var is visible here ... end |
- Transfer of control statements that can be used within loops:
break,next,redo- Can be combined with
ifandunlessmodifiers
- Can be combined with
begin
do_something # exception raised
rescue
# handles error
retry # restart from beginning
end- Functions and Methods are defined as blocks
def function_name ... end - The returned value is the value of the last statement. Or you can make the return value explicit by using the
returnkeyword. - Function arguments can have default values.
- Function arguments are passed by value. When the arguments passed are objects, the values passed are references.
- So in effect, you can modify the referenced object if you call its methods, but if you assign another object to the variable then you aren't affecting the original object anymore. This is similar to Java.
- If
argis a collection, then passing*argas argument expands the collection, and passes its individual members as items.- If
*argappears in the argument list for the function definition, that indicates a function with a variable number of arguments, which are then accessed by their index, e.g.arg[i]. - The
*operator is called a splat
- If
- When passing a hash literal as a parameter, braces can be omitted, e.g.
load_file :name => 'file.txt', :readonly => trueis equivalent toload_file ( { :name => 'file.txt', :readonly => true } )
- Blocks are code chunks delimited by
{ .. }ordo ... end - Blocks can be passed to methods, and executed from inside the method with
yield - Blocks can also be parametric:
{ |i,j| i + j; }
- Classes are defined as blocks
class ClassName ... end - Constructors are named
initialize - Object instances are created with
ClassName.new - Static methods can be declared by
def ClassName.method_name