A Ruby cheatsheet for beginners
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


Ruby cheatsheet

This is a cheatsheet for Ruby beginners and contains links to resources and some simple examples to get started with Ruby.


Linux/OSX: RVM (Ruby Version Manager) is the best way to manage Ruby installations on Linux and Mac OSX.

Windows: RubyInstaller is the quickest way to get Ruby installed on Windows.

Ruby Language Basics


The classic "hello world" program:

puts "Hello, world!"


Ruby strings belong to class String, and can be either single- or double- quoted.

'Hello, world!'        #=> "Hello, world!"
"Hello, world!".class  #=> String
"Hello".size           #=> 5


Ruby numbers beong to class Fixnum.

2 + 2           #=> 4
2.class         #=> Fixnum

2 + 1.5         #=> 3.5
3.5.class       #=> Float

Numbers larger than the integer size on the machine automatically get converted to Bignum object. So the size of numbers in Ruby is, in theory, only limited by the available memory on the machine.

2**100          #=> 1267650600228229401496703205376 
(2**100).class  #=> Bignum


Ruby variables are created when a value is assigned to them. Once created, a variable can be assigned another object of a different type, since Ruby variables don't have a fixed type.

x = 1                # x is a Fixnum object
x = x + 1.5          # x is now a Bignum

x = "Matz"           # x is now a string
puts "Hello, #{x}!"  #=> "Hello, Matz!"

You can also interpolate strings as shown in the above example. Anything inside #{...} gets evaluated and interpolated into the string.


Arrays can contain objects of different types. See some examples here:

items = [1, 2, 3]    #=> [1, 2, 3]
items << "a"         #=> [1, 2, 3, "a"]

# Also works like a list
x = items.pop       #   x contains value "a"
                    #   item = [1, 2, 3]
items.push("Matz")  #=> [1, 2, 3, "Matz"]


TODO: Add some content here.


TODO: Add some content here.

Objects and classes

Defining a class:

class Foo
  def initialize(name)
    @name = name

This creates a class called Foo. Classes are always named in CamelCase.

Constructor: The constructor method for a class should be named initialize. It gets called whenever a new instance of the class is created.

Instance variable: Variables that are prefixed with @ are instance variables. Here, @name is an instance variable of class Foo.

Creating objects: Create an object foo which is an instance of class Foo and initialize it with the name "bar".

foo = Foo.new("bar")


TODO: Add some content here.

Looping and iteration

TODO: Add some content here.

Online Ruby resources


  • Tryruby - Try Ruby in your browser.
  • Rubymonk - Interactive Ruby tutorials.