DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. Essential Ruby
refcard cover
Refcard #030

Essential Ruby

The Perfect Ruby Quick Reference

Provides a quick reference to the Ruby language, including language elements and many important API functions for quick look-up.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Peter Cooper
Manager, Poop Tech
Table of Contents
► About Ruby ► Ruby Language Overview ► Simple Ruby Examples ► IRB ► Ruby Gems ► Ruby Language Reference Tables ► Ruby 1.9 ► Resources
Section 1

About Ruby

By Melchior Brislinger and Peter Cooper

Ruby is an easy-to-learn, dynamic, object-oriented programming language with dynamic typing and automatic memory management. While object-oriented at heart, it provides facilities for procedural and functional programming as well as extensive support for introspection and meta-programming. Ruby's core API, extensive standard library, and thousands of high-quality external libraries make it suitable for many different programming tasks in multiple disciplines (key examples being network programming, Web applications, shell scripts, data processing, and text manipulation).

Ruby is already installed on Mac OS X and many Linux distributions. For Windows the easiest way to install everything necessary is the Ruby Installer (http://rubyinstaller.rubyforge.org).

This refcard provides a quick reference to language elements

and many important API functions for quick lookup.

Section 2

Ruby Language Overview

Ruby is considered to be a "pure" object-oriented language because almost every concept within Ruby is object-oriented in some sense. Yukihiro "Matz" Matsumoto, Ruby's creator, wanted to develop a language that operated on the "principle of least surprise" meaning that code should behave in a nonconfusing manner and be reasonably self-explanatory (beyond the basic syntax). Matz also wanted Ruby to be a pleasurable language with which to program, and not make unnecessary demands upon the programmer.

Ruby is considered a "reflective" language because it's possible for a Ruby program to analyze itself (in terms of its make-up), make adjustments to the way it works, and even overwrite its own code with other code. It's also considered to be "dynamically typed" because you don't need to specify what type of objects can be associated with certain variables. Objects are considered prime in Ruby and whether you're passing around a string, a number, a regular expression, or even a class, you're just dealing with an object from Ruby's point of view.

Ruby will seem reasonably familiar to Python and Perl programmers (and to a lesser extent C# and JavaScript developers) as Ruby was heavily inspired by Perl in certain areas (as was Python). Ruby is less similar to languages like C, C++ or Java because these languages are compiled (not interpreted), statically typed, and focused on performance rather than flexibility and conciseness.

Section 3

Simple Ruby Examples

Despite being an object-oriented language, it is not necessary to use explicitly object-oriented syntax within a basic Ruby program. While everything works on objects (and methods called upon those objects) behind the scenes, you can write a program as simply as this:

​x
1
​
2
def fib(i)
3
        if i.zero?
4
                0
5
        elsif i == 1
6
                1
7
        else
8
                fib(i - 2) + fib(i - 1)
9
        end
10
end
11
puts fib(10)
12
​

This script prints to screen the 10th number in the Fibonacci sequence. It defines a method called fib that returns the relevant result from a simple if/elsif/else expression. Note the use of standard equality syntax (==), addition (+), subtraction (-), and method calling (fib(10)), but also note the possibility of using methods in somewhat idiomatic ways (i.zero? rather than i == 0—though the latter would also work). The use of i.zero? demonstrates calling a method upon an object (where i is the object, and zero? is the method).

Hot Tip

The main Ruby interpreter is usually invoked by running "ruby" from the command line. If it is given a filename as an argument that file will be run (e.g. ruby myscript.rb). The interpreter has several other options that are listed in the "Ruby Interpreter Arguments" table in this card's reference section.

Developing a program with "true" object-oriented syntax is not significantly different. For example:

13
1
​
2
class Person
3
        attr_accessor :name, :age
4
​
5
        def full_info
6
                return "#{@name} is #{@age} years old"
7
        end
8
end
9
fred = Person.new
10
fred.name = "Fred"
11
fred.age = 45
12
puts fred.full_info
13
​

In this example, a class (Person) is defined, and attributes (name and age) and a method (full_info) are defined upon that class. Below the class definition, we then create an instance of the Person class and assign it to a variable, fred, before assigning values to its attributes, and then calling that instance's full_info method (which, in turn, uses instance variables—prefixed with @-to create its output).

Hot Tip

"This is a test" is a string with no special qualities (and, remember, it's also an object in Ruby) but it's possible to interpolate data into it (from variables, etc.) with a special syntax:

"2 plus 2 is #{2 + 2}"

The #{} construction serves to interpolate the result of the expression within the curly braces—in this case 2 + 2 is calculated to equal 4 and so the string ends up as "2 plus 2 is 4"

Earlier we called Ruby a "reflective" language because it offers functionality to programs to change, extend, and otherwise inspect themselves. We can look at a key Ruby idiom and reflective feature—class reopening—by changing the Fibonacci example from earlier to the following:

15
1
​
2
class Integer
3
        def fib
4
                if self.zero?
5
                        0
6
                elsif self == 1
7
                        1
8
                else
9
                        (self - 2).fib + (self - 1).fib
10
                end
11
        end
12
end
13
​
14
puts 10.fib
15
​

Note this time that in order to get the Fibonacci number, we're no longer calling a global fib method, but a method that works directly upon the number 10 itself (remember, everything is an object—even the number 10!). The way this is achieved is by "reopening" a standard Ruby class—Integer—and defining a new method called fib within it. This then makes the fib method available to all objects of class Integer in Ruby! Note that the content of the integer object itself (the number we need to use) is obtained with the self keyword. self, in this case, returns a representation of the current object in its native form. In this sense, Ruby is very similar to Python.

Section 4

IRB

IRB (short for "Interactive Ruby") is an interactive prompt or "Read-Eval-Print-Loop" (REPL) that uses the Ruby interpreter. Anything you type is evaluated by Ruby and the response printed to screen. IRB can be invoked by running "irb" from the command. A demonstrative session shows the usage:

20
1
​
2
irb(main):001:0> 3 + 5
3
=> 8
4
​
5
irb(main):002:0> "hello there " * 3
6
=> "hello there hello there hello there "
7
​
8
irb(main):001:0> "A String".class
9
=> String
10
​
11
irb(main):002:0> "A String".methods.sort
12
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==",
13
"===", "=~", ">", ">=", "[]", "[]=", "__id__", "__
14
send__", "all?", ...
15
​
16
irb(main):003:0> "A String".class.methods.sort
17
=> ["<", "<=", "<=>", "==", "===", "=~", ">", ">=",
18
"__id__", "__send__", "allocate", "ancestors",
19
"autoload", ...
20
​

IRB is most commonly used when learning the Ruby programming language, and also as a handy "sand box" to try out new programming tricks and techniques quickly. IRB can be used to interactively explore classes, test pieces of code and is also used as a console to inspect and manipulate running programs, for example, in Web applications.

Hot Tip

Want to try Ruby without installing anything?
Or want to get a walkthrough tutorial? Go to http://tryruby.hobix.com. It's a Web-based version of IRB and Ruby, and features a tutorial to bring you up to speed.
Section 5

Ruby Gems

RubyGems is the official Ruby package manager (though, notably, it is not included with default Ruby 1.8 releases by default— although it is present within Ruby 1.9 and on the OS X version of Ruby 1.8). It allows developers and users to easily search, install and update Ruby libraries and their dependencies and works in a similar fashion to other package management tools (such as yum and apt-get).

Gems are installed by running "gem install" and the name of the gem (e.g. gem install rails). Running "gem update" updates all installed gems to their latest official versions.

A selection of popular Ruby gems/libraries:

gem/library Description URL
Rails The famous Web application framework http://www.rubyonrails.com
Rake A Ruby based build system(like a Ruby equivalent of make) http://rake.rubyforge.org
Capistrano A tool for automatic remote deployment tasks http://capify.org
Mongrel A Ruby Web server and HTTP daemon library http://mongrel.rubyforge.org
rspec A "Behavior Driven Development" (BDD) framework http://rspec.info
camping A tiny web framework http://code.whytheluckystiff.net/camping

Information about RubyGems can be found at: http://www.rubygems.org

Section 6

Ruby Language Reference Tables

The following reference tables provide a quick look at many elements of Ruby's syntax. These can be used as a comparison to other languages in order to see how the syntax differs. Ruby's syntax is often rather different to that of, say, Java or C#.

Types

123 Integer (Fixnum or Bignum)
12345 1.23e-4 Float
0xFF00 0b01100 0244 Integer as hexadecimal, binary, or octal
1..5 'a'..'z' Range (inclusive)
1...5 'a'...'z' Range (non-inclusive – e.g. 1…5 represents 1 through 4)
?c Character
'string' String
"string\n" Double-quoted String with escape character
"string #{...}" Double-quoted String with inline expressions
<<DOC
string
DOC
Heredoc String
:symbol Symbol
/regexp/opts Regexp (regular expression)
[123, 'string', object, :symbol ] Array
{1 => 2, :symbol =>'string' } Hash (associative array)

Literals

%q %Q(string) Single/double-quoted String
%w %W(string string string) Array of Strings (no quotes for the Strings)
%r(regexp) Regexp (regular expression)

Variables

local Locally scoped variable
@instance Instance scoped variable
@@class Class scoped variable
$global Globally scoped variable
Constant Constant
4
1
​
2
if condition
3
...
4
end


8
1
​
2
if condition
3
...
4
elsif condition
5
...
6
else
7
...
8
end


6
1
​
2
unless condition
3
...
4
else
5
...
6
end


2
1
​
2
... if condition


2
1
​
2
... unless condition


2
1
​
2
condition ? ... : ... (a ternary operator)


7
1
​
2
case ...
3
when condition
4
...
5
else
6
...
7
end


4
1
​
2
while condition
3
...
4
end


4
1
​
2
until condition
3
...
4
end


4
1
​
2
do
3
...
4
while condition


4
1
​
2
do
3
...
4
until condition


4
1
​
2
for object in enumerable
3
...
4
end


5
1
​
2
break
3
next
4
redo
5
retry


2
1
​
2
yield arguments


Modules and Classes

4
1
​
2
module Name
3
...
4
end


Defines a module
4
1
​
2
class Name < Super
3
...
4
end


Defines a class with a superclass
4
1
​
2
class << SomeClass
3
...
4
end


Defines /accesses the singleton class of SomeClass— suited for defining class methods rather than instance methods
2
1
​
2
include Module


Includes module in class
4
1
​
2
def name(arguments)
3
...
4
end


Defines instance method
7
1
​
2
def Class.name(arguments)
3
...
4
end
5
def self.name(arguments)
6
...
7
end


Defines class method
4
1
​
2
public
3
protected
4
private


Methods below are public/protected/private
4
1
​
2
public symbol
3
protected symbol
4
private symbol


Methods with names supplied as symbols are public/protected/private
5
1
​
2
attr symbols
3
attr_accessor symbols
4
attr_reader symbols
5
attr_writer symbols


Creates accessor methods for all variables given
alias :new_method_name :method_name Creates alias for method with name
super(arguments) Calls same method of superclass

Constants

__FILE__ Filename of current source code file
__LINE__ Current line
__END__ End of Ruby code (ignore everything below)
DATA Anything below __END__ as an IO/File object
ENV[] Environment Variables
ARGV[ ] ARGF[ ] Command Line Arguments

Exceptions

10
1
​
2
begin
3
...
4
rescue exception => variable
5
...
6
else
7
...
8
ensure
9
...
10
end


Try a block of code and catch possible exceptions

Figure 1 shows the Exception hierarchy.

Exception hierarchy

Ruby Tools

ruby The Ruby interpreter
irb An interactive Ruby prompt
ri symbol Shows documentation for the specified symbol
rdoc Generates HTML documentation form Ruby source files
gem RubyGems, the Ruby package manager—not always available by default

Ruby Interpreter Arguments

-c Check code
-d Debug
-e "..." Execute a single line expression
-h Help
-rLibrary require the specified library
-v Verbose mode
-w Display code warnings
-y Enable compiler debug mode
-rubygems Loads RubyGem support

Regular Expressions

. Any character (excluding newlines)
[...] Any single character in set
[^...] Any single character not in set
* Zero or more
+ One or more (to as many as possible)
+? One or more (to as few as possible)
? Zero or one
| (pipe symbol) Alternatives (e.g. a|b|c will match a, b, or c)
(...) Group
^ Beginning of line or string
$ End of line or string
{n, m} n to m (as a quantity)
(?>...) Atomic group
(?=...) Lookahead
(?!...) Negative lookahead
\N Back reference N (where N is a digit)
\A Beginning of a string
\b Word boundary
\B Non-word boundary
\d Digit
\D Non-digit
\s Whitespace
\S Non-whitespace
\w Word-character (alphanumeric)
\W Non-word-character
\z End of a string
\Z End of string, before newline
/.../imx Case insensitive, multiline, ignore whitespace

Ruby Core API

Figure 2 shows important Core API classes and their inheritance tree.

Core API classes

The following is a selection of important Ruby Core API objects and methods. Instance methods are written .method and called object.method while class methods are written #method and called Class.method.

Object

.class Returns the object's class
.inspect Returns a string containing information about the object
.instance_eval
.instance_eval { ... }
String code
Block
Evaluates a string or block in the context of the object
.is_a?
.kind_of?
Class class
Class class
Returns true if the object's class equals the argument
.methods Returns an array with the object's methods
.nil? Returns true if the object equals nil
.respond_to? Symbol methodname Returns true if the object responds to the method
.send Symbol methodname, [arguments] Sends the message to the object along with optional arguments
.to_s Returns a string of the object

Enumerable

.all? { |object| ... } Sends all elements to the block and returns true if every block returned true
.any? { |object| ... } Sends all elements to the block and returns true if any block returned true
.map { |object| ... } Sends all elements to the block and returns a new Array with each result
.find { |object| ... }
.detect { |object| ... }
Sends all elements to the block and returns the first element for which the blocks result is not false
.find_all { |object| ... }
.select { |object| ... }
Sends all elements to the block and returns all elements for which the block is not false
.grep Object pattern Returns a new Array with all elements for which pattern === element
.include? Object object Returns true if the collection includes object
.sort [{|object, object| ... }] Returns the Array, sorted by each elements <=> or by the block

Array (Enumerable)

[]
[]
[]
Fixnum index
Fixnum start,
Fixnum length
Range range
Returns the object at the specified index or all objects in the specified range
.compact Returns the Array without element that equal nil
.delete Object object Deletes object from the Array
.delete_at Fixnum index Deletes the object at index from the Array
.delete_if { |object| ... } Deletes elements for which the block returns true
.each { |object| ... } Sends each element to the block
.flatten Flattens the Array
.index Object object Returns the index of the first occurrence of object
.insert Fixnum index,
Object object
Inserts object at the position specified by index
.join String separator Returns a String with all elements separated by separator
.length Returns the number of elements
.pop Returns the last element and removes it
.push Object object... Pushes object to the end of the Array
.reverse Reverses the order of elements
.rindex Object object... Returns the index of the last occurrence of object
.shift Returns the first element and removes it
.uniq Returns a new Array without duplicates
.unshift Object object... Pushes object to the front of the Array

Hash (Enumerable)

[ ] Object key Returns the value for key
[ ] = value Object key Sets the value for key
.delete Object key Deletes key and value from the Array
.delete_if { |key, value| ... } Deletes key and value for which block returns true
.each { |key, value| ... } Sends each key and value to the block
.each_key { |key| ... } Sends each key to the block
.each_value { |value| ... } Sends each value to the block
.include?
.key?
Object object...
Object object...
Returns true if the hash includes a value for key
.value? Object object... Returns true if the collection includes a key for value
.index Object object... Returns the key for value
.invert Returns a new Hash with keys and values inverted
.keys Returns an Array with all keys from the Hash
.length Returns the number of key-value pairs
.merge Hash hash... Returns a new Hash with entries from both Hashes
.select { |object| ... } Returns an Array with key-value pairs for which the block returns true
.to_a Returns an Array with nested key-value pairs
.values Returns an Array with all values from the Hash

String (Enumerable)

[ ]
[ ]
[ ]
Fixnum index
Range range
Regexp regexp
Returns the specified character or string
.capitalize Returns a capitalized version of the string
.center Fixnum width,
[String filler]
Centers the string using spaces or a specified filler string
.chomp [String separator] Returns a String with separator removed from the end
.count Returns the number of characters
.downcase Returns a lowercase version of the string
.gsub Regexp regexp
String replacement
Replaces all occurrences of regexp with replacement
.gsub { |string...| ... } Regexp regexp Finds all occurrences of regexp and replaces them with the result of the block
.index String/Regexp piece Returns the position of the first occurrence of piece
.rindex String/Regexp piece Returns the position of the last occurrence of piece
.scan { |string...| ... } Regexp regexp Scans the string for occurrences of regexp and passes them to the block
.split String string Splits the string into an array and returns it
.strip Returns a string with whitespace removed from both ends
.swapcase Returns a version of the string with uppercase turned to lowercase and vice-versa
.to_sym Returns a symbol named like the string
.upcase Returns an uppercase version of the string

IO

#read String filename [,
Fixnum length]
Opens filename and reads at most length bytes
#readline String file, [ ] Reads and returns a line from file
.close Closes the IO
.each_line { |string| ... } Send each line to the block
.eof? Returns true if there is no more data to read
.print Object object Writes object to the IO
.printf String string,
[Object object...]
Formats and writes string to the IO
.puts Object object Writes object to the IO
.read [Fixnum length] Reads and returns at most length bytes
.readline Reads and returns a line

File < IO

#basename String path [, String suffix] Returns the filename from path with or without suffix
#exist? String filename Returns true if filename exists
#join String piece [, String piece] Returns path by joining pieces
#new { |file| ... } String filename, String options Opens and sends filename to block
#new String filename, String options Opens and returns filename
#size String filename Returns the filesize of filename

File options

r/r+ Read/read-write from start of file
w/w+ Write/read-write truncate if file exists or create new
a/a+ Write/read-write from the end of the existing file or create new

Struct

.each { |object| ... } Calls the block for each instance variable passing the value
.each_pair
{ |symbol, object| ... }
Calls the block for each instance variable passing the name and value
.length Returns the number of instance variables
.members Returns an Array containing all instance variable names
#new [Symbol name, ...] Creates a new Struct with an instance variable for each symbol

Kernel

block_given? Returns true if a block was passed to the method
fork { ... } Creates a subprocess, runs the block in it and returns its ID
open String filename Opens a file
open { |io| ... } String filename Opens a file, passes it to the block and closes it afterwards
p Object object Prints object to the stdio
printf String string,
[Object object...]
Formats and writes string to the stdio
lambda {|object...| ... } Creates and returns a new proc object with the supplied block
puts String string Writes object to the IO
require String filename Load a Ruby file
system(string[,string...]) String command [, args] Executes a system command
Section 7

Ruby 1.9

Ruby 1.9 is the new version of Ruby considered transitional to Ruby 2.0 containing many changes to the language and libraries. It has an entirely new virtual machine and bytecode compiler, formerly known as YARV.

The new version includes support for unicode in strings, the famous Oniguruma regular expression engine as well as Operating System Threads and Fibers for lightweight concurrency.

Important Syntax Additions/Differences to Ruby 1.8

Syntax Additions/Differences Ruby 1.9 Ruby 1.8
Hash literal syntax { key: "value" } { :key => "value" }
Additional Proc/lambda definition syntax foo = ->(a,b){ ... } foo = lambda { |a,b| ... }
Additional Proc/lambda call syntax foo.("x", "y") foo.call("x", "y")
Block local variables foo = lambda { |;a| ... }
Encoding support for String "foo".encoding
String indices return Strings "foo"[2] # => "o" "foo"[2] # => 111
Optional arguments are possible before and after other arguments
4
1
​
2
def foo(a, b = 2, c, d = 3)
3
...
4
end


External Iterators i = [1, 2, 3].each
Section 8

Resources

The official Ruby website http://www.ruby-lang.org
The official documentation http://www.ruby-doc.org
The main Ruby repository http://www.rubyforge.org
Wikipedia's overview of Ruby http://en.wikipedia.org/wiki/Ruby_(programming_language)
The Ruby mailing lists http://www.ruby-forum.com
Ruby Zone http://ruby.dzone.com/
An interactive online tutorial http://tryruby.hobix.com (no download or installation)
A Ruby news site http://www.rubyinside.com
A community-powered Ruby news site http://www.rubyflow.com/
A Ruby-related blog aggregator http://www.rubycorner.com
JRuby (Java Ruby Implementation) http://jruby.codehaus.org
IronRuby (.NET Ruby Implementation) http://www.ironruby.net

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Ruby: Open A File, Write To It, And Close It In One Line
related article thumbnail

DZone Article

Swap Elements Of An Array In Ruby
related article thumbnail

DZone Article

Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
related article thumbnail

DZone Article

The Cypress Edge: Next-Level Testing Strategies for React Developers
related refcard thumbnail

Free DZone Refcard

Getting Started With Low-Code Development
related refcard thumbnail

Free DZone Refcard

JavaScript Test Automation Frameworks
related refcard thumbnail

Free DZone Refcard

Salesforce Application Design
related refcard thumbnail

Free DZone Refcard

E-Commerce Development Essentials

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: