Data Types

Numbers:

a = 123
a = 123
b = 1_234
c = 123.45
d = 1.2e-3

Strings:

'no interpolation'
"#{interpolation} and backslashes\n"

Symbols:

A symbol is an immutable name used for identifiers, variables, and operators.

:symbol

Ranges:

1..10
'a'..'z'
(1..10)  # inclusive
(1...10) # exclusive

Arrays:

[1, 2, 3]
%w(foo bar baz)    # no interpolation
%W(foo #{bar} baz) # interpolation

Hashes:

{ number: 1, string: 'hi' }

Variables and Constants:

$global_variable
@instance_variable
[OtherClass::]CONSTANT # eg. Math::PI
local_variable

Control Operations

if a > b
  # body
elsif b > a
  # body
else
  # body
end
unless a > b   # 'unless a == b' is same as 'if a != b'
  # body
else
  # body
end
do_something if a > b
do_something unless a == b
a > b ? do_something_if_true : do_something_if_false
case grade
when "A"
  puts 'Well done!'
when "B"
  puts 'Try harder!'
when "C"
  puts 'You need help!!!'
else
  puts "You just making it up!"
end

Loops

while conditional [do]
   code
end

code while condition

begin
  code
end while conditional
until conditional [do]
   code
end

code until conditional

begin
   code
end until conditional
(expression).each do |variable[, variable...]|
  code
end
for i in 0..5
   if i > 2 then
      break   # use break to exit the loop
   end
   puts "Value of local variable is #{i}"
end

Methods

# define
def method_name
   expr..
   # By default returns the evaluation of the last line of code
   # 'return' is optional
end

def method_name (var1, var2, optional_val = value)
   expr..
end

# invoke
method_name
method_name(var1, var2)

Classes

class Identifier < Superclass
  # Accessors
  attr_reader
  attr_writer
  attr_accessor

  def initializer (var1, var2)
    @var1 = var1
    @var2 = var2
  end

  def public_method
    # ...
  end

  protected
  # accessable only by instances of class and direct descendants

  private
  # accessable only by instances of class

end
b = B.new(va1, var2)
b.class_method

Modules

module Identifier
  # ...
end

Exceptions

class InvalidUserInput < Exception
end

begin
  puts "Select a column to place an \'#{color}\' piece:"
  move = gets.chomp.to_i

  # checks if user tries to play a move outside the board
  raise InvalidUserInput.new("Invalid input. Select a number between 1 and [email protected]_num}") unless move.between?(1, @col_num)
  # checks if user tries to play a move at a full column
  raise InvalidUserInput.new("You can't put another checker in row #{move}.") unless @board[move-1].length < @row_num

rescue InvalidUserInput => error
  puts error
  retry
end

References