Skip to content

Instantly share code, notes, and snippets.

@skarabasakis
Last active August 29, 2015 14:20
Show Gist options
  • Save skarabasakis/7d2cb4c428c673c33435 to your computer and use it in GitHub Desktop.
Save skarabasakis/7d2cb4c428c673c33435 to your computer and use it in GitHub Desktop.
Ruby Syntax Basics

Ruby Syntax Basics

General

  • Line endings separate statements. Semicolons optional.
  • Line comments begin with #
  • Block comments enclosed by =begin and =end

Operators

  • Arithmetical: +,-,*,/,%,** (exponent)
  • Comparison: ==,!=,>,>=,<,<=,<=>,===
    • Equality checking methods: eq? (same value and type), equal? (same reference)
  • Bitwise: & (and), | (or), ^ (xor), ~ (not), <<, >>
  • Logical: and, or, not or &&, ||, !

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 defined
    • undef cancels a symbol definition
    • alias defines another global reference for the same symbol

Variables

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__

Booleans

  • The only falsey value in Ruby is nil. Everything else is truthy, including the numeric 0.

Strings

  • String interpolation: "#{foo} is a #{bar}".
    • Expressions in #{...} are eval'ed
    • String interpolation allowed in heredocs.
  • Heredocs (starting with <<) supported for defining long strings.
  • String Concatenation: the << operator appends to the string on the left, e.g. "append" == "app" << "end"

Arrays

  • 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, -1 indicating the last element
  • 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 }
  • Also supported: casting a range to an array nums = Array(0..9)
  • Methods size and length return the array length

Array operations

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

Hashes

  • 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

  • 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 ...,

Arrays, Hashes and Ranges are examples of collections, i.e. enumerable objects with methods such as each and collect.

Conditional Blocks

if conditional
  # ...
elsif conditional
  # ...
else
  # ...
end
unless conditional
  # ...
else
  # ...
end
case expression
when expression, expression 
  # ...
else
  # ...
end
  • if and unless can also be used as modifiers, e.g. x = a / b unless b == 0

Iteration blocks

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 if and unless modifiers

Exceptions

begin
   do_something # exception raised
rescue
   # handles error
   retry  # restart from beginning
end

Functions and Methods

  • 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 return keyword.
  • 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 arg is a collection, then passing *arg as argument expands the collection, and passes its individual members as items.
    • If *arg appears 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
  • When passing a hash literal as a parameter, braces can be omitted, e.g. load_file :name => 'file.txt', :readonly => true is equivalent to load_file ( { :name => 'file.txt', :readonly => true } )

Blocks

  • Blocks are code chunks delimited by { .. } or do ... 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

  • 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment