Skip to content

Ruby Quick Guide

This guide provides a concise overview of key Ruby concepts and syntax elements, updated for modern Ruby practices.

Ruby is a dynamic, open-source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. Created by Yukihiro “Matz” Matsumoto in Japan in the mid-1990s, Ruby is a pure object-oriented language where everything is an object.

irb is Ruby’s interactive shell (REPL). It allows you to execute Ruby code snippets and see immediate results, making it great for experimentation and learning. Simply type irb in your terminal to start.

  • Whitespace: Generally ignored, except in string literals. Indentation is for readability.
  • Line Endings: Newlines typically end statements. Semicolons (;) can separate multiple statements on one line but are rarely used.
  • Identifiers: Names for variables, methods, etc. Case-sensitive. Conventions: snake_case for variables/methods, CamelCase for classes/modules, UPPER_SNAKE_CASE for constants.
  • Comments: Single-line with #. Multi-line with =begin and =end (each on its own line).

Words with special meaning, e.g., if, else, while, class, def, module, end, true, false, nil. (Refer to the Syntax chapter for a more comprehensive list).

For multi-line strings. <<DELIMITER, <<'DELIMITER' (no interpolation), and <<~DELIMITER (squiggly heredoc, removes leading whitespace) are common.

name = "Alice"
message = <<~TEXT
Hello, #{name}!
Welcome to the system.
TEXT
puts message

Numbers:

  • Integer: Whole numbers (e.g., 123, -50, 0, 1_000_000). Ruby handles large integers automatically (formerly distinct Fixnum and Bignum).
  • Float: Numbers with a decimal point (e.g., 3.14, -0.001, 2.0e3).

Strings: Sequences of characters.

  • Single-quoted ('...'): Literal strings, minimal interpolation (only \' and \\).
  • Double-quoted ("..."): Support interpolation (#{expression}) and escape sequences (e.g., \n, \t).
  • Percent strings: %q{...} (literal, like single quotes), %Q{...} or %{...} (interpolated, like double quotes).

Symbols: Lightweight, immutable identifiers, often used as hash keys or for referencing method names. Start with a colon (e.g., :name, :status).

Booleans: true and false.

nil: Represents the absence of a value.

Arrays: Ordered collections of objects. Literal: [1, "two", :three].

Hashes (Dictionaries): Collections of key-value pairs.

  • Older syntax: {"name" => "Bob", "age" => 30}
  • Modern syntax (Ruby 1.9+) for symbol keys: {name: "Alice", age: 25} (This is equivalent to {:name => "Alice", :age => 25})

Ranges: Represent an interval. (1..5) (inclusive: 1,2,3,4,5), (1...5) (exclusive: 1,2,3,4).

  • Local variables: my_variable (scope limited to current block, method, or file).
  • Instance variables: @my_variable (belong to an instance of a class).
  • Class variables: @@my_variable (shared among a class and all its instances; use with care due to inheritance behavior).
  • Global variables: $my_variable (accessible from anywhere; generally discouraged).
  • Constants: MY_CONSTANT (value should not change after initialization; lexically scoped).

Special variables that cannot be assigned to:

  • self: The receiver object of the current method.
  • true, false, nil: Singleton instances representing these values.
  • __FILE__: Name of the current source file.
  • __LINE__: Current line number in the source file.
  • __ENCODING__: The script encoding of the current file.

Selected Predefined Variables (use modern alternatives where possible):

Section titled “Selected Predefined Variables (use modern alternatives where possible):”

Ruby has many Perl-style predefined global variables. While they exist, modern Ruby often favors more descriptive method calls. Here are a few:

VariableDescription
$!The last exception object raised. (Use rescue => e to capture).
$@The stack backtrace for the last exception. (Use e.backtrace).
$/Input record separator (newline by default).
$.Line number of the last line read by gets from the current input file (ARGF.lineno).
$<Alias for ARGF (virtual concatenation of files from arguments or STDIN).
$0Name of the current Ruby script being executed.
$$Process ID of the current Ruby script.
$LOAD_PATH or $:Array of directories searched when loading files with require.
$stdin, $stdout, $stderrDefault standard input, output, and error streams.

The $SAFE variable and its security levels are largely historical and not considered a robust security mechanism for modern applications. Rely on other security practices.

ConstantDescription
TRUE, FALSE, NILDeprecated uppercase versions of true, false, nil. Avoid.
ARGFStream for reading from files in ARGV or STDIN.
ARGVArray of command-line arguments.
ENVHash-like access to environment variables.
RUBY_VERSIONString with the current Ruby version (e.g., “3.2.2”).
RUBY_PLATFORMString identifying the interpreter platform.
STDIN, STDOUT, STDERRStandard I/O streams.

Literals: /pattern/, %r{pattern}. Options: i (ignore case), m (multiline - . matches newline), x (extended - ignores whitespace, allows comments).

Example: `name = "John Doe"; if name =~ /john/i then puts "Match found!" end`

Best practice is to use File.open with a block to ensure the file is closed automatically.

File.open("my_file.txt", "r") do |file|
file.each_line do |line|
puts line
end
end
File.write("output.txt", "Hello from Ruby!") # Simple way to write a file

Modes: "r" (read), "w" (write, truncates), "a" (append), "r+" (read-write), etc.

Ruby has a rich set of operators, most of which are methods. Precedence (highest to lowest, simplified):

  • ::, . (Access)
  • [] (Element access), ** (Exponentiation)
  • !, ~, unary +, - (Not, Bitwise NOT, Unary plus/minus)
  • *, /, % (Multiplication, Division, Modulo)
  • +, - (Addition, Subtraction)
  • <<, >> (Bitwise shifts)
  • & (Bitwise AND)
  • |, ^ (Bitwise OR, XOR)
  • >, >=, <, <= (Comparison)
  • <=>, ==, ===, !=, =~, !~ (Equality, Pattern matching)
  • && (Logical AND)
  • || (Logical OR)
  • .., ... (Range creation)
  • Ternary: ? :
  • Assignment: =, +=, -=, etc.
  • not (Logical NOT, lower precedence)
  • and, or (Logical AND/OR, lower precedence)

Use parentheses () to clarify order or force precedence when in doubt.

  • if condition ... elsif condition ... else ... end
  • unless condition ... else ... end (executes if condition is false)
  • Postfix if/unless: statement if condition
  • case expression when value ... else ... end
  • while condition ... end
  • until condition ... end
  • Iterators (preferred for collections): collection.each { |item| ... }, n.times { ... }, collection.map { ... }
  • for item in collection ... end (less common than each)
  • Loop control: break (exit loop), next (skip to next iteration), redo (restart current iteration), retry (mostly in rescue blocks to restart begin block).
class MyClass
attr_accessor :name # Creates getter & setter for @name
def initialize(name)
@name = name
end
def greet
"Hello, #{@name}!"
end
def self.class_method # A class method
"I am a class method."
end
end
module MyModule
def utility_method
"This is a utility."
end
end
class AnotherClass
include MyModule # Mixes in MyModule's instance methods
end
obj = MyClass.new("RubyDev")
puts obj.greet
puts MyClass.class_method
util_obj = AnotherClass.new
puts util_obj.utility_method

Access Control: public (default), protected, private (applied to methods below them).

begin
# Code that might raise an exception
result = 10 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
rescue SomeOtherError => e
puts "Another type of error: #{e.message}"
else
# Executes if no exceptions were raised
puts "No errors! Result: #{result}"
ensure
# Always executes, whether an exception occurred or not
puts "Cleaning up..."
end

Raising exceptions: raise "My custom error" or raise ArgumentError, "Invalid argument".

OptionDescription
-cCheck syntax only, don’t execute.
-e 'program'Execute the given string as a program.
-r libraryRequire the library before executing.
-wEnable verbose warnings.
-v or --versionDisplay Ruby version.
--helpDisplay help message.
VariableDescription
RUBYLIBPath for Ruby to search for libraries (augments $LOAD_PATH).
RUBYOPTCommand-line options to be passed to Ruby implicitly.
GEM_HOMEDirectory where gems are installed.
GEM_PATHPaths where RubyGems will look for gems.

This quick guide covers many essential aspects of Ruby. For deeper understanding, refer to comprehensive Ruby books and the official Ruby documentation.