Ruby Quick Guide
Ruby Quick Reference Guide
Section titled “Ruby Quick Reference Guide”This guide provides a concise overview of key Ruby concepts and syntax elements, updated for modern Ruby practices.
What is Ruby?
Section titled “What is Ruby?”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 (Interactive Ruby Shell):
Section titled “IRB (Interactive Ruby Shell):”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.
Core Syntax:
Section titled “Core Syntax:”- 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_casefor variables/methods,CamelCasefor classes/modules,UPPER_SNAKE_CASEfor constants. - Comments: Single-line with
#. Multi-line with=beginand=end(each on its own line).
Reserved Words (Keywords):
Section titled “Reserved Words (Keywords):”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).
Here Documents (Heredocs):
Section titled “Here Documents (Heredocs):”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.TEXTputs messageBasic Data Types:
Section titled “Basic Data Types:”Numbers:
Integer: Whole numbers (e.g.,123,-50,0,1_000_000). Ruby handles large integers automatically (formerly distinctFixnumandBignum).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).
Variable Types and Scope:
Section titled “Variable Types and Scope:”- 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).
Pseudo-Variables:
Section titled “Pseudo-Variables:”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:
| Variable | Description |
|---|---|
$! | 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). |
$0 | Name 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, $stderr | Default 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.
Selected Predefined Constants:
Section titled “Selected Predefined Constants:”| Constant | Description |
|---|---|
TRUE, FALSE, NIL | Deprecated uppercase versions of true, false, nil. Avoid. |
ARGF | Stream for reading from files in ARGV or STDIN. |
ARGV | Array of command-line arguments. |
ENV | Hash-like access to environment variables. |
RUBY_VERSION | String with the current Ruby version (e.g., “3.2.2”). |
RUBY_PLATFORM | String identifying the interpreter platform. |
STDIN, STDOUT, STDERR | Standard I/O streams. |
Regular Expressions (Regex):
Section titled “Regular Expressions (Regex):”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`File I/O:
Section titled “File I/O:”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 endend
File.write("output.txt", "Hello from Ruby!") # Simple way to write a fileModes: "r" (read), "w" (write, truncates), "a" (append), "r+" (read-write), etc.
Operators and Precedence (Simplified):
Section titled “Operators and Precedence (Simplified):”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.
Control Flow:
Section titled “Control Flow:”if condition ... elsif condition ... else ... endunless condition ... else ... end(executes if condition is false)- Postfix
if/unless:statement if condition case expression when value ... else ... endwhile condition ... enduntil condition ... end- Iterators (preferred for collections):
collection.each { |item| ... },n.times { ... },collection.map { ... } for item in collection ... end(less common thaneach)- Loop control:
break(exit loop),next(skip to next iteration),redo(restart current iteration),retry(mostly inrescueblocks to restartbeginblock).
Defining Classes and Modules:
Section titled “Defining Classes and Modules:”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." endend
module MyModule def utility_method "This is a utility." endend
class AnotherClass include MyModule # Mixes in MyModule's instance methodsend
obj = MyClass.new("RubyDev")puts obj.greetputs MyClass.class_method
util_obj = AnotherClass.newputs util_obj.utility_methodAccess Control: public (default), protected, private (applied to methods below them).
Exception Handling:
Section titled “Exception Handling:”begin # Code that might raise an exception result = 10 / 0rescue 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..."endRaising exceptions: raise "My custom error" or raise ArgumentError, "Invalid argument".
Ruby Command Line Options (Common):
Section titled “Ruby Command Line Options (Common):”| Option | Description |
|---|---|
-c | Check syntax only, don’t execute. |
-e 'program' | Execute the given string as a program. |
-r library | Require the library before executing. |
-w | Enable verbose warnings. |
-v or --version | Display Ruby version. |
--help | Display help message. |
Environment Variables (Common):
Section titled “Environment Variables (Common):”| Variable | Description |
|---|---|
RUBYLIB | Path for Ruby to search for libraries (augments $LOAD_PATH). |
RUBYOPT | Command-line options to be passed to Ruby implicitly. |
GEM_HOME | Directory where gems are installed. |
GEM_PATH | Paths 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.