RUBY
RUBY
What is Ruby?
Ruby is a dynamic, open source, object oriented and reflective programming language. It runs on all types of
platforms like Windows, Mac OS and all versions of UNIX.
It is fully object-oriented programming language. Everything is an object in Ruby. Each and every code has their
properties and actions. Here properties refer to variables and actions refer to methods.
Ruby is considered to follow the principle of POLA (principle of least astonishment). It means that the language
behaves in such a way to minimize the confusion for experienced users.
History of Ruby
Ruby is designed and developed by Yukihiro
"Martz" Matsumoto in mid 1990s in Japan.
FEATURES OF RUBY
Object Oriented - Ruby is purely object-oriented programming language. Each and every value is an object.
Every object has a class, and every class has a super class. Every code has their properties and actions. Ruby is
influenced with Smalltalk language. Rules applying to objects applies to the entire Ruby.
Flexibility - Ruby is a flexible language as you can easily remove, redefine or add existing parts to it. It allows its
users to freely alter its parts as they wish.
Mixins - Ruby has a feature of single inheritance only. Ruby has classes as well as modules. A module has
methods but no instances. Instead, a module can be mixed into a class, which adds the method of that module
to the class. It is similar to inheritance but much more flexible.
Visual appearance - Ruby generally prefers English keyword and some punctuation is used to decorate Ruby. It
doesn't need variable declaration.
Dynamic typing and Duck typing - Ruby is a dynamic programming language. Ruby programs are not compiled.
All class, module and method definition are built by the code when it run.
Ruby variables are loosely typed language, which means any variable can hold any type of object. When a
method is called on an object, Ruby only looks up at the name irrespective of the type of object. This is duck
typing. It allows you to make classes that pretend to be other classes.
Exception handling
Garbage collector
Portable
Keywords - In Ruby there are approximately 42 keywords which can't be used for other purposes. They are
called reserved words.
Statement delimiters - Multiple statements in a single line must contain semi colon in between but not at the
end of a line.
Variable constants - In Ruby, constants are not really constant. If an already initialized constant will be modified
in a script, it will simply trigger a warning but will not halt your program.
Naming conventions - Ruby defines some naming conventions for its variable, method, constant and class.
Ruby Operators
Ruby has a built-in modern set of operators. Operators are a symbol which is used to perform different
operations. For example, +, -, /, *, etc.
Types of operators:
Unary operator
Arithmetic operator
Bitwise operator
Logical operator
Ternary operator
Assignment operator
Comparison operator
Range operator
Unary Operator
Operator Description
! Boolean NOT
~ Bitwise complement
+ Unary plus
Example
puts("Unary operator")
puts(~5)
puts(~-5)
puts(!true)
puts(!false)
Output:
Unary operator
-6
4
false
true
Arithmetic Operator
Arithmetic operators take numerical values as operands and return them in a single value.
Operator Description
% Divide left side operand with right side operand returning remainder.
Example
puts("add operator")
puts(10 + 20)
puts("subtract operator")
puts(35 - 15)
puts("multiply operator")
puts(4 * 8)
puts("division operator")
puts(25 / 5)
puts("exponential operator")
puts(5 ** 2)
puts("modulo operator")
puts(25 % 4)
Output:
add operator
30
subtract operator
20
multiply operator
32
division operator
5
exponential operator
25
modulo operator
1
Bitwise Operator
Operator Description
| OR operator
^ XOR operator
~ Complement operator
Logical Operator
Operator Description
|| OR operator
Ternary Operator
Ternary operators first check whether given conditions are true or false, then execute the condition.
Operator Description
?: Conditional expression
Example
puts("Ternary operator")
puts(2<5 ? 5:2)
puts(5<2 ? 5:2)
Output:
Ternary operator
5
2
Assignment Operator
Operator Description
Comparison Operator
Operator Description
== Equal operator
Example
puts("Comparison operator")
puts(2 == 5)
puts(2 != 5)
puts(2 > 5)
puts(2 < 5)
puts(2 >= 5)
puts(2 <= 5)
Output:
Comparison operator
false
true
false
true
false
true
Range Operator
Range operators create a range of successive values consisting of a start, end and range of values in between.
The (..) creates a range including the last term and (...) creates a range excluding the last term.
For example, for the range of 1..5, output will range from 1 to 5.
and for the range of 1...5, output will range from 1 to 4.
Operator Description
Ruby Variables
Ruby variables are locations which hold data to be used in the programs. Each variable has a different name.
These variable names are based on some naming conventions. Unlike other programming languages, there is no
need to declare a variable in Ruby. A prefix is needed to indicate it.
Local variables
Class variables
Instance variables
Global variables
Local variables
A local variable name starts with a lowercase letter or underscore (_). It is only accessible or have its scope
within the block of its initialization. Once the code block completes, variable has no scope. When uninitialized
local variables are called, they are interpreted as call to a method that has no arguments.
Class variables
A class variable name starts with @@ sign. They need to be initialized before use. A class variable belongs to the
whole class and can be accessible from anywhere inside the class. If the value will be changed at one instance, it
will be changed at every instance. A class variable is shared by all the descendants of the class. An uninitialized
class variable will result in an error.
Instance variables
An instance variable name starts with a @ sign. It belongs to one instance of the class and can be accessed from
any instance of the class within a method. They only have limited access to a particular instance of a class. They
don't need to be initialized. An uninitialized instance variable will have a null value.
Global variables
A global variable name starts with a $ sign. Its scope is globally, means it can be accessed from anywhere in a
program. An uninitialized global variable will have a null value. It is advised not to use them as they make
programs cryptic and complex. There are a number of predefined global variables in Ruby.
Summary
Scope Limited within the Its scope is It belongs to one Limited to the
block of globally. instance of a whole class in
initialization. class. which they are
created.
Numbers
Strings
Symbols
Hashes
Arrays
Booleans
Numbers
Integers are held internally in binary form. Integer numbers are numbers without a fraction. According to their
size, there are two types of integers. One is Bignum and other is Fixnum.
Class Description Example
Strings
A string is a group of letters that represent a sentence or a word. Strings are defined by enclosing a text within
single (') or double (") quote.
Symbols
Symbols are like strings. A symbol is preceded by a colon (:). For example,
:abcd
They do not contain spaces. Symbols containing multiple words are written with (_). One difference between
string and symbol is that, if text is a data, then it is a string but if it is a code, it is a symbol.
Symbols are unique identifiers and represent static values, while string represent values that change.
Hashes
A hash assigns its values to its keys. They can be looked up by their keys. Value to a key is assigned by => sign. A
key/value pair is separated with a comma between them and all the pairs are enclosed within curly braces. For
example,
Arrays
An array stores data or list of data. It can contain all types of data. Data in an array are separated by comma in
between them and are enclosed by square bracket. For example,
Elements from an array are retrieved by their position. The position of elements in an array starts with 0.
The Ruby if else statement is used to test condition. There are various types of if statement in Ruby.
if statement
if-else statement
if-else-if (elsif) statement
ternay (shortened if statement) statement
Ruby if statement
Ruby if statement tests the condition. The if block statement is executed if condition is true.
Syntax:
if (condition)
//code to be executed
end
Example:
a = gets.chomp.to_i
if a >= 18
puts "You are eligible to vote."
end
Output:
22
You are eligible to vote.
Ruby if else
Ruby if else statement tests the condition. The if block statement is executed if condition is true otherwise else
block statement is executed.
Syntax:
if(condition)
//code if condition is true
else
//code if condition is false
end
Example:
a = gets.chomp.to_i
if a >= 18
puts "You are eligible to vote."
else
puts "You are not eligible to vote."
end
Output:
22
16
Ruby if else if statement tests the condition. The if block statement is executed if condition is true otherwise
else block statement is executed.
Syntax:
if(condition1)
//code to be executed if condition1is true
elsif (condition2)
//code to be executed if condition2 is true
else (condition3)
//code to be executed if condition3 is true
end
Example:
a = gets.chomp.to_i
if a <50
puts "Student is fail"
elsif a >= 50 && a <= 60
puts "Student gets D grade"
elsif a >= 70 && a <= 80
puts "Student gets B grade"
elsif a >= 80 && a <= 90
puts "Student gets A grade"
elsif a >= 90 && a <= 100
puts "Student gets A+ grade"
end
Output:
75
Student gets B grade
In Ruby ternary statement, the if statement is shortened. First it evaluates an expression for true or false value
then execute one of the statements.
Syntax:
test-expression ? if-true-expression : if-false-expression
Example:
var = gets.chomp.to_i;
a = (var > 3 ? true : false);
puts a
Output
5
true
2
false
In Ruby, we use 'case' instead of 'switch' and 'when' instead of 'case'. The case statement matches one statement
with multiple conditions just like a switch statement in other languages.
Syntax:
case expression
[when expression [, expression ...] [then]
code ]...
[else
code ]
end
Example:
print "Enter your day: "
day = gets.chomp
case day
when "Tuesday"
puts 'Wear Red or Orange'
when "Wednesday"
puts 'Wear Green'
when "Thursday"
puts 'Wear Yellow'
when "Friday"
puts 'Wear White'
when "Saturday"
puts 'Wear Black'
else
puts "Wear Any color"
end
Output:
Ruby for loop iterates over a specific range of numbers. Hence, for loop is used if a program has fixed number of
iterations.
Ruby for loop will execute once for each element in expression.
Syntax:
for variable [, variable ...] in expression [do]
code
end
Output:
enter a value: 5
1
2
3
4
5
Example:
x = ["Blue", "Red", "Green", "Yellow", "White"]
for i in x do
puts i
end
Output:
Blue
Red
Green
Yellow
White
Ruby while loop executes a condition while a condition is true. Once the condition becomes false, while loop
stops its execution.
Syntax:
while conditional [do]
code
end
Example:
print “enter a value: ”
x = gets.chomp.to_i
while x >= 0
puts x
x -=1
end
Output:
enter a value: 5
5
4
3
2
1
0
The Ruby do while loop iterates a part of program several times. It is quite similar to a while loop with the only
difference that loop will execute at least once. It is due to the fact that in do while loop, condition is written at
the end of the code.
Syntax:
loop do
#code to be executed
break if booleanExpression
end
Example:
loop do
puts "Checking for answer"
answer = gets.chomp
if answer != '5'
break
end
end
Output:
Checking for answer
5
Checking for answer
The Ruby until loop runs until the given condition evaluates to true. It exits the loop when condition becomes
true. It is just opposite of the while loop which runs until the given condition evaluates to false.
Syntax:
until conditional
code
end
Example:
i=1
until i == 10
print i*10, "\n"
i += 1
end
Output:
10
20
30
40
50
60
70
80
90
The Ruby break statement is used to terminate a loop. It is mostly used in while loop where value is printed till
the condition is true, then break statement terminates the loop. The break statement is called from inside the
loop.
Syntax:
break
Example:
i=1
while true
if i*5 >= 25
break
end
puts i*5
i += 1
end
Output:
5
10
15
20
The Ruby next statement is used to skip loop's next iteration. Once the next statement is executed, no further
iteration will be performed. The next statement in Ruby is equivalent to continue statement in other languages.
Syntax:
next
Example:
for i in 5...11
if i == 7 then
next
end
puts i
end
Output:
5
6
8
9
10
Ruby redo statement is used to repeat the current iteration of the loop. The redo statement is executed without
evaluating the loop's condition. The redo statement is used inside a loop.
Syntax:
redo
Example:
i=0
while(i < 5) # Prints "012345" instead of "01234"
puts i
i += 1
redo if i == 5
end
Output:
0
1
2
3
4
5
Ruby retry statement is used to repeat the whole loop iteration from the start. The retry statement is used
inside a loop.
Syntax:
retry
Ruby Comments
Ruby comments are non-executable lines in a program. These lines are ignored by the interpreter hence they
don't execute while execution of a program. They are written by a programmer to explain their code so that
others who look at the code will understand it in a better way.
The Ruby single line comment is used to comment only one line at a time. They are defined with # character.
Syntax:
#This is single line comment.
Example:
i = 10 #Here i is a variable.
puts i
Output:
The Ruby multi line comment is used to comment multiple lines at a time. They are defined with =begin at the
starting and =end at the end of the line.
Syntax:
=begin
This
is
multi line
comment
=end
Example:
=begin
we are declaring
a variable i
in this program
=end
i = 10
puts i
Ruby Object
Object is the default root of all Ruby objects. Ruby objects inherit from BasicObject (it is the parent class of all
classes in Ruby) which allows creating alternate object hierarchies.
Creating object
Objects in Ruby are created by calling new method of the class. It is a unique type of method and predefined in
the Ruby library. Ruby objects are instances of the class.
Syntax:
objectName = className.new
Example:
# class name is box
class Box
# class variable
@@No_of_color = 3
end
# Two Objects of Box class
sbox = Box.new
nbox = Box.new
Ruby Class
Each Ruby class is an instance of class Class. Classes in Ruby are first-class objects.
Ruby class always starts with the keyword class followed by the class name. Conventionally, for class name we
use CamelCase. The class name should always start with a capital letter. Defining class is finished with end
keyword.
Syntax:
class ClassName
codes...
end
Example:
# class name is Animal
class Animal
# class variables
@@type_of_animal = 4
@@no_of_animal = 3
end
RUBY ARRAYS
Ruby arrays are ordered collections of objects. They can hold objects like integer, number, hash,
string, symbol or any other array.
Its indexing starts with 0. The negative index starts with -1 from the end of the array. For example, -1
indicates last element of the array and 0 indicates first element of the array.
Output
4
4.0
Jose
Syntax:
arrayName = Array.new
Example:
exm = Array.new(10)
puts exm.size
puts exm.length
Output:
10
10
Ruby array elements can be accessed using #[] method. You can pass one or more than one arguments or even a
range of arguments.
Example:
Output
Mon
-------
-------
Sat
-------
Wed
Thu
Fri
-------
Tue
Wed
Thu
Fri
Sat
Sun
at method
To access a particular element, at method can also be used.
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.at(0)
puts table.at(-1)
puts table.at(5)
Output
6
60
36
fetch method
The fetch method is used to provide a default value error for out of array range indices.
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.fetch(10)
Output
HelloWorld.rb:2:in `fetch': index 10 outside of array bounds: -10...10 (IndexError)
from HelloWorld.rb:2:in `<main>'
Output
6
60
take method
The take method returns the first n elements of an array.
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.take(4)
Output:
6
12
18
24
drop method
The drop method is the opposite of take method. It returns elements after n elements have been
dropped.
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.drop(4)
Output:
30
36
2
48
54
60
push or <<
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.push(4)
puts table << (15)
Output:
6
12
18
24
30
36
2
48
54
60
4
15
unshift
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.unshift(15)
Output:
15
6
12
18
24
30
36
2
48
54
60
insert
Using insert, a new element can be added at any position in an array. Here, first we need to mention the index
number at which we want to position the element.
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.insert(3,15)
Output:
6
12
18
15
24
30
36
2
48
54
60
pop
shift
delete
uniq
pop
Using pop, items can be removed from the end of an array. It returns the removed item.
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.pop
Output:
60
shift
Using shift, items can be removed from the start of an array. It returns the removed item.
Example:
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.shift
Output:
6
delete
Using delete, items can be removed from anywhere in an array. It returns the removed item.
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.delete(36)
Output:
36
uniq
Using uniq, duplicate elements can be removed from an array. It returns the remaining array.
Example:
table=[6,12,18,12,30,6]
puts table.uniq
Output:
6
12
18
30
Reverse
Displays the elements of the array in the reverse order
Example:
table=[6,12,18,30]
puts table.reverse
Output:
30
18
12
6
include
checks whether a particular element is present in the array or not returns true if present or returns false
Example:
table=[6,12,18,30]
puts table.include?(4)
puts table.include?(12)
Output:
false
true
sort
sorts the array elements in ascending order
Example:
table=[12,6,30,18]
puts table.sort
Output:
6
12
18
30
Output:
12
6
30
18
60
2
48
-returns elements present in first array and absent in the second array
Example:
table=[12,6,24,30,18,54]
tables=[12,6,30,18]
puts table-tables
Output:
24
54
RUBY METHODS
Ruby methods prevent us from writing the same code in a program again and again. It is a set of expression
that returns a value.
Ruby methods are similar to the functions in other languages. They unite one or more repeatable
statements into one single bundle.
Defining Method
To use a method, we need to first define it. Ruby method is defined with the def keyword followed by
method name. At the end we need to use end keyword to denote that method has been defined.
Methods name should always start with a lowercase letter. Otherwise, it may be misunderstood as a
constant.
Syntax:
def methodName
code...
end
You can set default values for the parameters, which will be used if method is called without
passing the required parameters
def methodName(var1=val1,var2=val2)
code...
end
Whenever you call the simple method, you write only the method name as follows −
method_name
However, when you call a method with parameters, you write the method name along with the
parameters, such as −
method_name 25, 30
Example:
def test(a1 = "Ruby", a2 = "Perl")
puts "The programming language is #{a1}"
puts "The programming language is #{a2}"
end
test "C", "C++"
test
Output:
The programming language is C
The programming language is C++
The programming language is Ruby
The programming language is Perl
Output:
100
200
300
Output:
The number of parameters is 3
The parameters are mlac
The parameters are 6
The parameters are z
The number of parameters is 0
RUBY BLOCKS
Ruby code blocks are called closures in other programming languages. It consist of a group of codes which is
always enclosed with braces or written between do..end. The braces syntax always have the higher precedence
over the do..end syntax. Braces have high precedence and do has low precedence.
To invoke a block, you need to have a function with the same name as the block.
A block is always invoked with a function. Blocks can have their own arguments.
syntax:
block_name{
statement1
statement2
..........
}
Multiline Block
Example:
[10, 20, 30].each do |n|
puts n
end
Output:
10
20
30
Inline Block
Example:
[10, 20, 30].each {|n| puts n}
Output:
10
20
30
The yield statement is used to call a block within a method with a value.
Example:
def met
puts "This is method"
yield
puts "You will be back to method"
yield
end
met {puts "This is block"}
Output:
This is method
This is block
You will be back to method
This is block
While the execution of met method, when we reach at yield line, the code inside the block is
executed. When block execution finishes, code for met method continues.
Output:
This is block 1
This is method
This is block 2
RUBY STRINGS
Ruby string object holds and manipulates an arbitary sequence of bytes, typically representing characters. They
are created using String new or as literals.
Ruby string literals are enclosed within single and double quotes.
Example:
puts 'Hello everyone'
puts "Hello everyone"
Output:
Hello everyone
Hello everyone
Output:
Google
tutorial
T
Th
This tutorial is fro
This tutorial is from Google.
g
Multiline string
Writing multiline string is very simple in Ruby language. We will show three ways to print multi line string.
→ String can be written within double quotes.
→ The % character is used and string is enclosed within / character.
→ we use << and string is enclosed within word STRING.
→ String can be written within double quotes.
Example:
puts "
A
AB
ABC
ABCD"
Output:
A
AB
ABC
ABCD
Output:
A
AB
ABC
ABCD
Output:
A
AB
ABC
ABCD
Variable Interpolation
Ruby variable interpolation is replacing variables with values inside string literals. The variable name is put
between #{ and } characters inside string literal.
Example:
country = "India"
capital = "New Delhi"
puts "#{capital} is the capital of #{country}."
Output:
New Delhi is the capital of India.
Concatenating Strings
Ruby concatenating string implies creating one string from multiple strings. You can join more than one string to
form a single string by concatenating them.
There are four ways to concatenate Ruby strings into single string:
Example:
string = "Good " + "Morning!"
puts string
Output:
Good Morning!
Example:
string = "Good " "Morning!"
puts string
Output:
Good Morning!
Example:
string = "Good " << "Morning!"
puts string
Output:
Good Morning!
4) Using concat method in between strings.
Example:
string = "Good ".concat("Morning!")
puts string
Output:
Good Morning!
Freezing Strings
In most programming languages strings are immutable. It means that an existing string can't be modified, only a
new string can be created out of them.
In Ruby, by default strings are not immutable. To make them immutable, freeze method can be used.
Example:
str = "Original string"
str << " is modified "
str << "is again modified"
puts str
str.freeze
#str << "And here modification will be failed after using freeze method"
Output:
Original string is modified is again modified
In the above output, we have made the string immutable by using freeze method. Last line is
commented as no string can be modified any further.
By uncommenting the last line, we'll get an error as shown in the below output.
Output:
Original string is modified is again modified
HelloWorld.rb:9:in `<main>': can't modify frozen String: "Original string is modified is again modified"
(FrozenError)
Comparing Strings
Example:
puts "abc" == "abc"
puts "as ab" == "ab ab"
puts "23" == "32"
Output:
true
false
false
Example:
puts "ttt".eql? "ttt"
puts "12".eql? "11"
Output:
true
false
Example:
Output:
0
1
String Substitution
Sometimes the substring of a string that matched a pattern must be replaced by another string. Ruby’s String
class has two methods to do that.
1. sub
2. gsub
sub - takes two parameters, a pattern and a string. sub matches the pattern against the string object. If sub finds
a match, the matched substring is replaced by its second parameter.
Example:
str = "The old car is great, but old."
puts str.sub(/old/,"new")
Output:
The new car is great, but old.
gsub - it is similar to sub, but finds all substring matches and replaces all of them with its second parameter
Example:
str = "The old car is great, but old."
puts str.gsub(/old/,"new")
puts str
Output:
The new car is great, but new.
The old car is great, but old.
Notice from the last line that gsub does not alter the string object on which it is called. The same is true for
sub. However, sub and gsub have mutator versions, named sub! and gsub!.
Example:
str = "The old car is great, but old."
puts str.gsub!(/old/,"new")
puts str
Output:
The new car is great, but new.
The new car is great, but new.
Example:
str = "Is it Rose, rose or ROSE?"
puts str.gsub(/rose/,"lily")
Output:
Is it Rose, lily or ROSE?
In the above example, the case of the letters is not considered. So, the i modifier, which tells the pattern
matcher to ignore the case of letters, can also be used with the substitute method by attaching it to the
right end of the pattern as shown in the following code:
Example:
str = "Is it Rose, rose or ROSE?"
puts str.gsub(/rose/i,"lily")
Output:
Is it lily, lily or lily?
RUBY HASHES
A Ruby hash is a collection of unique keys and their values. They are similar to arrays but array use integer as an
index and hash use any object type. They are also called associative arrays, dictionaries or maps.
If a hash is accessed with a key that does not exist, the method will return nil.
Syntax:
name = {"key1" => "value1", "key2" => "value2", "key3" => "value3"...}
OR
name = {key1: 'value1', key2: 'value2', key3: 'value3'...}
Example:
ages = {
"John"=>38,
"Genny"=>36,
"Jake"=>22,
"Darcie"=>21
}
puts ages
puts ages["Genny"]
ages["Aiden"]=17
puts ages
ages.delete("Genny")
puts ages
puts ages.has_key?("John")
puts ages.has_key?("Henry")
puts ages.keys
puts ages.values
Output:
{"John"=>38, "Genny"=>36, "Jake"=>22, "Darcie"=>21}
36
{"John"=>38, "Genny"=>36, "Jake"=>22, "Darcie"=>21, "Aiden"=>17}
{"John"=>38, "Jake"=>22, "Darcie"=>21, "Aiden"=>17}
true
false
John
Jake
Darcie
Aiden
38
22
21
17