Getting Started with Ruby

It is impossible to cover everything in just one blog post. But the aim is to cover just enough to get you started. It is 90% of code sample with 10% of explanation. Therefore, I have to say that it will be easier to follow if you have prior experience with any other programming language. For a total beginner, Codecademy provide an awesome Ruby lesson and it’s Free.

Start With The Basic Syntax

You can start to write some Ruby code right away in some online editor. I will talk about installing Ruby runtime and IDE in Part2 of this post.

Comments (yes, start with the comment.)

single line comment:

# start a line with hash
# single line comment just like this

multiline comment:

Here you can have your
multiline comments.

Console Playground


print "Hello,"
print "World"
#console: Hello,World
print "Ruby"; print ",World"
#console: Ruby,World
#Ruby does not require semicolon(;) to end a line,
#but it can be use to join multiple line of code into one.


puts is like print, but it will display the result in newline automatically

puts 'Hello,'
puts 'World'
#console: Hello,

reading user input

#Getting user input
puts "What is your name? "
var_name = gets.chomp
puts "Hi there! #{var_name}"
#console: Hi there! terrence

Types & Variable

# string can be single quote or double quote
var_text1 = 'hello world'
var_text2 = "hello world"
var_num = 123
var_dec = 1.23
var_bool = true
puts var_text1==var_text2   #true

Ruby is dynamically AND strongly typed(more theory here). This mean that the type of a variable can change on the fly in runtime. The ruby compiler will happily accept the following code.

my_var = 123
my_var = 'abc' #I just assigned a string to a int variable
my_var = true #again, assigned a bool to a string variable
puts my_var
#console: true

Arithmetic Operators

num1 = 3
num2 = 2
num3 = 2.0
sum = num1+num2        #sum: 5
subtract = num1-num2 #subtract: 1
product = num1*num2 #product: 6
divide = num1/num2 #divide: 1
devide_dec = num1/num3 #devide_dec: 1.5
mod = num1%2 #mod: 1
exp = num1**2 #exp: 9

Conditional Assignment

var_num = 1
# comparison operator: ==, !=, <, >, <=, >=, &&, ||
if var_num == 0
puts 'value is origin'
elsif var_num > 0 #Note that it's elsif NOT elseif
puts 'value is positive'
puts 'value is negative'
console: value is positive

the reverse of ‘if’ using ‘unless’

var_bool = true
unless var_bool
puts "this is false"
puts "this is true"
console: this is true

shorthand using ‘unless’

var_num = 2
puts 'number is positive' unless var_num<0 'number is negative'
console: number is positive

Running In A Loop


i = 0
while i < 3
puts i
i += 1
#console: 0


i = 0
until i > 2
puts i
i += 1
#this until loop yield the exactly same 
#output as the above while loop.


with three dot notation (…)

for num in 1...3
puts num
#console: 1

with two dot notation (..)

for num in 1..3
puts num
#console: 1


3.times {
print 'x,'
console: x,x,x,


loop { puts "Hello, world!" }
#it can also be written like this:
loop do
puts "Hello, world!"
#don't do this. It will result in an infinity loop.

We need a break.


i = 0
loop {
puts i
i += 1
break if (i>5)


for i in 1..5
next if i % 2 == 0
print i

Array In Ruby

my_array = [1,2,3]
#multi dimension array
my_2d_array = [[1,2,3],[4,5,6]]
#Array can contain value of different type
types_array = [1,'a',2.3,true]

accessing array by index

my_array = ['Arnold','Jeff']
my_2d_array = [[1,2],[3,4]]
puts my_array[1]
puts my_2d_array[1][0]
#console: Jeff

looping through an array

my_array = [1,2,3,4,5]
my_array.each do |x|
print "#{x}"
#curly bracket version
#my_array.each { |x| print "#{x}" }
console: 12345

looping through a multi-dimension array

array = [['a','b','c'],['d','e','f'],['g','h','i']]
array.each { |sub_array|
sub_array.each {|ele|
print ele
console: abcdefghi


array = [['a','b','c'],['d','e','f'],['g','h','i']]
array.each { |x,y,z|
print "#{x}#{y}#{z}"
console: abcdefghi

Hash In Ruby

Hash is a key-value pair object in Ruby

#declare a hash using literal notation
my_hash = {
"name" => "terrence",
"age" => 20
#declare a hash using new
my_new_hash = #same as my_new_hash={}
#adding kay-value pair to the hash
my_new_hash["name"] = "Yogurt"
my_new_hash["price"] = 2.3

using new to declare hash

my_hash =
my_hash['a'] = 123
print "value of a: #{my_hash["a"]}, value of x: #{my_hash["x"]}"
#console: value of a: 123, value of x: 999

looping through a hash is like looping through a multi-dimension array

family = {
"dad" => "Peter",
"mum" => "Lily",
"sis" => "Susan"
family.each { |x,y|
puts "#{y} is my #{x}"
console: Peter is my dad
Lily is my mum
Susan is my sis


The syntax for hash declaration with symbol has been changed since Ruby v1.9. But it’s good to know both new and old syntax, so that when you read code that use this old syntax, you know what is going on.

at this point, we have been using string as key in hash. However, the more Rubyist’s way is by using symbol. It also improve the performance as Hash lookup is faster with symbol as key.

#symbol is like variable but start will a colon(:)
family = {
:dad => "Peter",
:mum => "Lily",
:sis => "Susan"
puts family[:dad]

symbol can be converted into string and vice versa

family = {
:dad => "Peter",
:mum => "Lily",
:sis => "Susan"
puts family['dad'.to_sym]   #'dad'.intern will work too
puts family[:'mum']
puts :dad.to_s
#console: Peter

new syntax in Ruby v1.9

#symbol key no longer need to start with (:)
#and arrow assignment to set value
family = {
dad: "Peter",
mum: "Lily",
sis: "Susan"
puts family[:dad]
#console: Peter

Defining Methods

def show_text
puts "Hello World"
show_text  #calling the method
console: Hello World

method with argument

def display_square(a)
put a**2;
display_square (2)
#console: 4

supply multiply arguments

def display_sum(a, b=5)  #b is default to the value 5
puts a+b
#console: 6


def display_sum(*x)
sum = 0;
x.each {
sum += val

puts sum
#console: 15

Time to go one level higher above method.


Class Car
def initialize(brand)
@brand = brand
  def move_forward()
puts "#{brand} moving forward!"
  def move_fackward()
puts "#{brand} moving backward!"

so after defining the Car class, we want to create an object with using it.

audi ="Audi")
#console: Audi moving forward!

in Ruby, you can inspect what is the method available in a class

#console: [:move_forward, :move_backward, :instance_of?, :public_send, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :private_methods, :kind_of?, :instance_variables, :tap,
:is_a?, :extend, :define_singleton_method, :to_enum,
:enum_for, :<=>, :===, :=~, :!~, :eql?, :respond_to?,
:freeze, :inspect, :display, :send, :object_id, :to_s,
:method, :public_method, :singleton_method, :nil?, :hash,
:class, :singleton_class, :clone, :dup, :itself, :taint,
:tainted?, :untaint, :untrust, :trust, :untrusted?, :methods,
:protected_methods, :frozen?, :public_methods, :singleton_methods,
:!, :==, :!=, :__send__, :equal?, :instance_eval, :instance_exec, :__id__]

Waitttt a second. Isn’t that we only have two methods in the class? Where is that long list of methods came from?

Turns out, those are the methods define in the ancestor classes. In this case, the default methods of ruby class. We can hide away those like this -

console: [:move_forward, :move_backward]

That is it… for now.

With these, I believe you have know enough to get started with Ruby. One thing you should have notice is that Ruby have a very human friendly syntax. Coding in Ruby almost feel like you are trying to explain the logic to the machine in english.

Ruby is a powerful language because of the support from the community, there are a tons of open source library out there. Check out Ruby On Rails for web development.