Ruby Reference
Here's a quick Ruby reference. See Learn Ruby for a full tutorial.
Printing in Ruby
To print to output in ruby, use the built-in method print
. To print with a newline at the end, use puts
.
Strings & Symbols
Strings can be declared with single or double quotes.
word1 = "hello"
word2 = 'hello'
Only double quotes allow interpolation of variables or code.
placeholder = "string interpolation"
"I can use #{placeholder} in double-quoted strings"
#=> "I can use string interpolation in double-quoted strings"
+
is used to concatenate strings together:
"hello " + "world" #=> "hello world"
Strings in Ruby can be accessed and edited like arrays:
str = "cat"
str[0] #=> "c"
Symbols in Ruby are immutable and are marked with a colon :
, like in :word
. Symbols are also often used as the keys in hashes.
Arrays and Hashes
Arrays are created with the square bracket syntax []
.
arr = [1, 2, 3, 4, 5]
arr[2] #=> 3
misc_array= [1, "hello", false]
Arrays can be accessed by index from the beginning or end:
arr[-1] #=> 5
Add an item to the end of an array with <<
, or
or set the value of a specific index:
arr << 6 #=> [1, 2, 3, 4, 5, 6]
arr[3] = 17
arr[8] = 7
arr #=> [1, 2, 3, 17, 5, 6, nil, nil, 7]
More methods for getting Array info:
arr.length #=> 6
arr.first #=> 1
arr.include?(3) #=> true
Ranges
Ranges are used for creating ordered sequences and are created with ..
syntax:
rang = 1..5
rang.to_a #=> [1, 2, 3, 4, 5]
arr[1..3] #=> [2, 3, 4]
Hashes
A Hash can be created with the curly-braces {}
syntax:
ha = {'color' => 'green', 'number' => 5}
ha.keys #=> ['color', 'number']
ha.values #=> ['green', 5]
hash['price'] = 72 #insertion, with any key
Hashes provide 'instant' lookups, and return nil
if the provided key isn't found:
hash['color'] #=> 'green'
hash['missing'] #=> nil
Often, symbols are used as keys, and Ruby provides a shortcut syntax, so these are equivalent:
ha2 = {:color => "blue", :number => 7}
ha2 = {color: "blue", number: 7}
ha2[:color] #=> "blue"
Both Arrays and Hashes are Enumerable.
Math and Logic
Ruby arithmetic operators:
1 + 1 #=> 2
10 * 2 #=> 20
35 / 5 #=> 7
10.0 / 4.0 #=> 2.5
4 % 3 #=> 1
2 ** 5 #=> 32
Equality and Comparisons
1 == 1 #=> true
2 != 1 #=> true
! true #=> false
not true #=> false
Logical Operators
true && true #=> true
false || true #=> true
true and false #=> false
true or false #=> true
Everything in ruby is considered true
except for false
and nil
:
!nil #=> true
!false #=> true
!1 #=> false
!0 #=> false
An or statement will return the first true value it encounters:
nil || 7 #=> 7
nil || false || 8 #=> 8
1 || 2 #=> 1
Control Structures
If Statement
energy = 4
if energy > 5
puts "Great!"
elsif energy == 4
puts "OK"
else
puts "Uh Oh!"
end
OK
Since energy
is 4, the code prints out "OK".
Ruby Loops
While loop example:
counter = 1
while counter <= 5
puts "iteration #{counter}"
counter += 1
end
...which prints:
iteration 1 iteration 2 iteration 3 iteration 4 iteration 5
The for loop goes through collections, such as a range, array or hash. This code will produce the same output as the while loop.
for counter in 1..5
puts "iteration #{counter}"
end
Methods
Here's a basic Ruby method with one parameter:
def double(x)
x * 2
end
Methods implicitly return the value of the last statement:
double 2 #=> 4
Multiple Parameters are separated with commas:
def sum(x,y)
x + y
end
sum 3, 4 #=> 7
Yield Block
You can pass around pieces of code with a block, which is marked with a do
and end
.
*(A block is similar to lambdas found in other languages.)
#method that takes block
def take_block
puts "before block"
yield
puts "after block"
end
# call method and pass it a block
take_block do
puts "i am block"
end
This will print out:
before block i am block after block
yield
calls the block that was passed into the method. Blocks can be surrounded with curly braces {}
instead of do
and end
:
take_block { puts "i am block" }
Each block parameters
Blocks can also take in parameters from the method they are passed to, which is what the each
method does:
(1..3).each do |index|
puts "number #{index}"
end
Output:
number 1 number 2 number 3
each
is used by the other ruby collections, such as arrays and hashes:
array.each do |element|
puts "#{element} is part of the array"
end
hash.each do |key, value|
puts "#{key} is #{value}"
end
map
maps all the items in a collection to new values, e.g. to return an array where each number has been doubled:
[1, 2, 3, 4].map do |n|
n*2
end
#=> [2, 4, 6, 8]
This tutorial is based in part on LearnXinYminutes and is licensed under the Creative Commons Attribution-ShareAlike 3.0 License.