[go: up one dir, main page]

0% found this document useful (0 votes)
13 views36 pages

RUBY

Ruby basics

Uploaded by

geethap.thogata
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views36 pages

RUBY

Ruby basics

Uploaded by

geethap.thogata
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

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.

Constant: Starts with a capital letter.


Global variable: Starts with a dollar sign ($).
Instance variable: Starts with a (@) sign.
Class variable: Starts with a (@@) sign.
Method name: Allowed to start with a capital letter.
Keyword arguments - Like Python, Ruby methods can also be defined using keyword arguments.
Method names - Methods are allowed to end with question mark (?) or exclamation mark (!). By convention,
methods that answer questions end with question mark and methods that indicates that method can change the
state of the object end with exclamation mark.
Singleton methods - Ruby singleton methods are per-object methods. They are only available on the object you
defined it on.
Missing method - If a method is lost, Ruby calls the method_missing method with name of the lost method.
Case Sensitive - Ruby is a case-sensitive language. Lowercase letters and uppercase letters are different.

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

Unary operators expect a single operand to run on.

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

+ Adds values from both sides of the operator.

- Subtract values from both sides of the operator.

/ Divide left side operand with right side operand.

* Multiply values from both sides of the operator.

** Right side operand becomes the exponent of left side operand.

% 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

Bitwise operators work on bits operands.

Operator Description

& AND operator

| OR operator

<< Left shift operator

>> Right shift operator

^ XOR operator

~ Complement operator

Logical Operator

Logical operators work on bits operands.

Operator Description

&& AND operator

|| 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

Assignment operator assign a value to the operands.

Operator Description

= Simple assignment operator

+= Add assignment operator

-= subtract assignment operator

*= Multiply assignment operator

/= Divide assignment operator

%= Modulus assignment operator

**= Exponential assignment operator

Comparison Operator

Comparison operators compare two operands.

Operator Description

== Equal operator

!= Not equal operator

> left operand is greater than right operand

< Right operand is greater than left operand

>= Left operand is greater than or equal to right operand

<= Right operand is greater than or equal to left operand

<=> Combined comparison operator

.eql? Checks for equality and type of the operands

equal? Checks for the object ID

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

.. Range is inclusive of the last term

... Range is exclusive of the last term

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.

There are four types of variables in Ruby:

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

Local Global Instance Class

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.

Naming Starts with a Starts with a $ Starts with an @ Starts with an


lowercase letter sign. sign. @@ sign.
or underscore (_).

Initialization No need to No need to No need to They need to be


initialize. An initialize. An initialize. An initialized before
uninitialized local uninitialized uninitialized use. An
variable is global variable instance variable uninitialized
interpreted as will have a nil will have a nil global variable
methods with no value. value. results in an error.
arguments.

Ruby Data types


Data types represents a type of data such as text, string, numbers, etc. There are different data types in Ruby:

Numbers
Strings
Symbols
Hashes
Arrays
Booleans

Numbers

Integers and floating point numbers come in the category of 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

Fixnum They are normal numbers 1

Bignum They are big numbers 111111111111

Float Decimal numbers 3.0

Complex Imaginary numbers 4 + 3i

Rational They are fractional numbers 9/4

BigDecimal Precision decimal numbers 6.0

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,

{"Akash" => "Physics", "Ankit" => "Chemistry", "Aman" => "Maths"}

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,

["Akash", "Ankit", "Aman"]

Elements from an array are retrieved by their position. The position of elements in an array starts with 0.

RUBY CONTROL STATEMENTS


Ruby If-else Statement

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

You are eligible to vote.

16

You are not eligible to vote.

Ruby if else if (elsif)

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

Ruby ternary Statement

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

Ruby Case Statement

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:

Enter your day: Friday


Enter your day: Wear White
Ruby for Loop

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

Ruby for loop using range


Example:
print “enter a value”
a = gets.chomp.to_i
for i in 1..a do
puts i
end

Output:

enter a value: 5

1
2
3
4
5

Ruby for loop using array

Example:
x = ["Blue", "Red", "Green", "Yellow", "White"]
for i in x do
puts i
end

Output:
Blue
Red
Green
Yellow
White

Ruby while Loop


The Ruby while loop is used to iterate a program several times. If the number of iterations is not fixed for a
program, while loop is used.

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

Ruby do while Loop

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

Ruby Until Loop

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

Ruby Break Statement

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

Ruby Next Statement

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

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

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.

Types of Ruby comments:

Single line comment


multi line comment

Ruby Single Line Comment

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 Class and Object


Object is a physical as well as logical entity whereas class is a logical entity only.

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.

Creating Ruby Arrays


A Ruby array is created in many ways.
Using literal constructor []
Using new class method

Using literal construct []


A Ruby array is constructed using literal constructor []. A single array can contain different type of
objects.
For example, following array contains an integer, floating number and a string.
exm = [4, 4.0, "Jose"]
puts exm

Output
4
4.0
Jose

Using new class method


A Ruby array is constructed by calling new method with zero, one or more than one argument.

Syntax:
arrayName = Array.new

To set the size of an array,


Syntax:
arrayName = Array.new(10)

Here, we have mentioned that array size is of 10 elements.


To know the size of an array, either size or length method is used.

Example:
exm = Array.new(10)
puts exm.size
puts exm.length

Output:
10
10

Accessing Array Elements

Ruby array elements can be accessed using #[] method. You can pass one or more than one arguments or even a
range of arguments.

Example:

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]


puts days[0]
puts "-------"
puts days[10]
puts "-------"
puts days[-2]
puts "-------"
puts days[2,3]
puts "-------"
puts days[1..7]

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>'

first and last method


The first and last method will return first and last element of an array respectively.
Example:
table=[6,12,18,24,30,36,2,48,54,60]
puts table.first
puts table.last

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

Adding Items to Array

Ruby array elements can be added in different ways.


push or <<
unshift
insert

push or <<

Using push or <<, items can be added at the end of an array.

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

Using unshift, a new element can be added at the beginning of an array.

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

Removing Items from Array

Ruby array elements can be removed in different ways.

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

+ concatenate two arrays


Example:
table=[12,6,30,18]
tables=[60,2,48]
puts table+tables

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 represent a method that accepts parameters like this


def methodName(var1,var2)
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

Return Values from Methods


The return statement in ruby is used to return one or more values from a Ruby Method.
Example:
def test
i = 100
j = 200
k = 300
return i, j, k
end
var = test
puts var

Output:
100
200
300

Variable Number of Parameters


Suppose you declare a method that takes two parameters, whenever you call this method, you need
to pass two parameters along with it.
However, Ruby allows you to declare methods that work with a variable number of parameters.
Example:
def sample (*test)
puts "The number of parameters is #{test.length}"
for i in 0...test.length
puts "The parameters are #{test[i]}"
end
end
sample "mlac", "6", "z"
sample

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.

A block is written in two ways,

Multi-line between do and end (multi-line blocks are niot inline)


Inline between braces {}

Both are same and have the same functionality.

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

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.

Passing parameters with yield statement


One or more than one parameter can be passed with the yield statement.
Example:
def met
yield 1
puts "This is method"
yield 2
end
met {|i| puts "This is block #{i}"}

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

Accessing string elements


You can access Ruby string elements in different parts with the help of square brackets []. Within square
brackets write the index or string.
Example:
msg = "This tutorial is from Google."
puts msg["Google"]
puts msg["tutorial"]
puts msg[0]
puts msg[0, 2]
puts msg[0..19]
puts msg[0, msg.length]
puts msg[-4]

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

→ The % character is used and string is enclosed within / character.


Example:
puts %/
A
AB
ABC
ABCD/

Output:
A
AB
ABC
ABCD

→ we use << and string is enclosed within word STRING.


Example:
message = <<-TEXT
A
AB
ABC
ABCD
TEXT
puts message

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:

1) Using plus sign in between strings.

Example:
string = "Good " + "Morning!"
puts string

Output:
Good Morning!

2) Using a single space in between strings.

Example:
string = "Good " "Morning!"
puts string

Output:
Good Morning!

3) Using << sign in between strings.

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

Ruby strings can be compared with three operators:

With == operator : Returns true or false

Example:
puts "abc" == "abc"
puts "as ab" == "ab ab"
puts "23" == "32"
Output:
true
false
false

With eql? Operator : Returns true or false

Example:
puts "ttt".eql? "ttt"
puts "12".eql? "11"

Output:
true
false

With casecmp method: Returns 0 if matched or 1 if not matched

Example:

puts "Java".casecmp "Java"


puts "Java".casecmp "ja"

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'...}

Creating Ruby Hash


Ruby hash is created by writing key-value pair within {} curly braces.
To fetch a hash value, write the required key within [] square bracket.

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

You might also like