Ruby Notesfinal1
Ruby Notesfinal1
B.Tech(cse).,M.Tech(cse).,Ph.D(cse).,Pdf(cse)
In order to compile the a ruby program, Open your text editor and save the program
with „.rb‟ extension. After this, go to terminal(or command prompt) and type : ruby
„file.rb‟ where file is the name of the program you just made, and hence the program will
be compiled.
Features of Ruby
Ruby has many reasons for being popular and in demand. Few of the reasons are
mentioned below:
1. The code written in Ruby is small, elegant and powerful as it has fewer number of
lines of code.
2. Ruby allows simple and fast creation of Web application which results in less hard
work.
3. As Ruby is free of charge that is Ruby is free to copy, use, modify, it allow
programmers to make necessary changes as and when required.
4. Ruby is a dynamic programming language due to which there is no tough rules on
how to built in features and it is very close to spoken languages.
Application Areas
3. Comments
• # is called the pound character in ruby and it is used to add comments to your code.
• =begin, =end are used for multi-line comments
Example:
# this is a comment and wont be executed
= begin
this is
a multi line
comment in ruby
= end
4. Maths: Simple mathematical functions can be carried out within the puts
statements.Just as we use „%d‟ or „%f‟ and „&‟ in C,we will use „#{ } in Ruby to get our
work done.
puts "Alok has #{25+30/6} Rupees in his pocket"
Output : Alok has 30 Rupees in his pocket
The use of #{ } is how you insert Ruby computations into text strings.
5. Variables and Names : Variables in ruby are the same as that of any other dynamic
programming language. You just don‟t need to mention its type and ruby will know its
type automatically.
Example:
cars = 100
drivers = 30
puts "There are #{cars} cars and #{drivers} drivers."
Output: There are 100 cars and 30 drivers.
6. Getting input
• „gets.chomp‟ is used to take input from user.
• „print‟ can be used instead for „puts‟to print without a new line.
Example:
print "How old are you ? "
age = gets.chomp
print "How tall are you ?"
height = gets.chomp
puts " You are #{age} year old and your height is #{height} cms"
Run this code on your system as output will be given by the user
Output:
Welcome to GFG portal
# variables of method
a = 10
b = 39
sum = a + b
end
Output:
The result is: 49
Looping in programming languages is a feature which clears the way for the execution
of a set of instructions or functions repeatedly when some of the condition evaluates to
true or false. Ruby provides the different types of loop to handle the condition based
situation in the program to make the programmers task simpler. The loops in Ruby are :
• while loop
• for loop
• do..while loop
• until loop
while Loop
The condition which is to be tested, given at the beginning of the loop and all
statements are executed until the given boolean condition satisfies. When the condition
becomes false, the control will be out from the while loop. It is also known as Entry
Controlled Loop because the condition to be tested is present at the beginning of the
loop body. So basically, while loop is used when the number of iterations is not fixed in
a program.
Syntax:
# code to be executed
end
Note: A while loop‟s conditional is separated from code by the reserved word do, a
newline, backslash(\), or a semicolon(;).
Flowchart:
Example:
• Ruby
# Ruby program to illustrate 'while' loop
# variable x
x = 4
# using while loop
# here conditional is x i.e. 4
while x >= 1
# statements to be executed
puts "GeeksforGeeks"
x = x - 1
# while loop ends here
end
Output:
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
for Loop
“for” loop has similar functionality as while loop but with different syntax. for loop is
preferred when the number of times loop statements are to be executed is known
beforehand. It iterates over a specific range of numbers. It is also known as Entry
Controlled Loop because the condition to be tested is present at the beginning of the
loop body.
Syntax:
# code to be executed
end
for: A special Ruby keyword which indicates the beginning of the loop.
variable_name: This is a variable name that serves as the reference to the current
iteration of the loop.
in: This is a special Ruby keyword that is primarily u sed in for loop.
expression: It executes code once for each element in expression. Here expression
can be range or array variable.
do: This indicates the beginning of the block of code to be repeatedly executed. do is
optional.
end: This keyword represents the ending of „for„ loop block which started from „do„
keyword.
Example 1:
• Ruby
i = "Sudo Placements"
puts i
end
Output:
Sudo Placements
Sudo Placements
Sudo Placements
Sudo Placements
Sudo Placements
Output:
1
2
3
4
5
Explanation: Here, we have defined the range 1..5. 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. The statement for a in 1..5 will allow a to take
values in the range from 1 to 5 (including 5).
Example 2:
# array
arr = ["GFG", "G4G", "Geeks", "Sudo"]
puts i
end
Output:
GFG
G4G
Geeks
Sudo
do..while Loop
do while loop is similar to while loop with the only difference that it checks the condition
after executing the statements, i.e it will execute the loop body one time for sure. It is
a Exit-Controlled loop because it tests the condition which presents at the end of the
loop body.
Syntax:
loop do
# code to be executed
break if Boolean_Expression
end
Here, Boolean_Expression will result in either a true or false output which is created
using comparing operators (>, =, <=, !=, ==). You can also use multiple boolean
expressions within the parentheses (Boolean_Expressions) which will be connected
through logical operators (&&, ||, !).
9.step 1, -2 do |x|
Example:
• Ruby
puts "GeeksforGeeks"
val = '7'
Output:
GeeksforGeeks
until Loop
Ruby until loop will executes the statements or code till the given condition evaluates to
true. Basically it‟s just opposite to the while loop which executes until the given
condition evaluates to false. An until statement‟s conditional is separated from code by
the reserved word do, a newline, or a semicolon.
Syntax:
end
Example:
• Ruby
var = 7
# code to be executed
puts var * 10
var = var + 1
Output:
70
80
90
100
In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly
used in while loop, where value is printed till the condition, is true, then break statement
terminates the loop.
Syntax :
Break
Example :
# Ruby program to use break statement
#!/usr/bin/ruby -w
i = 1
Output:
3
6
9
12
15
18
In examples, break statement used with if statement. By using break statement the execution will
be stopped. in above example, when i*3 will be greater than equal to 21 than execution will be
stopped.
Example :
# Ruby program to use break statement
#!/usr/bin/ruby -w
x = 0
# Using while
while true do
# Printing Value
puts x
x += 1
Output:
0
1
2
3
The above code restricts the number of loop iterations to 3.
next Statement :
To skip the rest of the current iteration we use next statement. When next statement is executed no
other iteration will be performed. next statement is similar as continue statement in any other
language.
Syntax:
next
Example :
# Ruby program of using next statement
#!/usr/bin/ruby -w
for x in 0..6
# Used condition
if x+1 < 4 then
# Printing values
puts "Value of x is : #{x}"
end
Output :
Value of x is : 3
Value of x is : 4
Value of x is : 5
Value of x is : 6
In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly
used in while loop, where value is printed till the condition, is true, then break statement
terminates the loop.
Syntax :
Break
Example :
# Ruby program to use break statement
#!/usr/bin/ruby -w
i = 1
# Using While Loop
while true
# Printing Values
puts i * 3
i += 1
if i * 3 >= 21
Output:
3
6
9
12
15
18
In examples, break statement used with if statement. By using break statement the execution will
be stopped. in above example, when i*3 will be greater than equal to 21 than execution will be
stopped.
Example :
# Ruby program to use break statement
#!/usr/bin/ruby -w
x = 0
# Using while
while true do
# Printing Value
puts x
x += 1
Output:
0
1
2
3
The above code restricts the number of loop iterations to 3.
next Statement :
To skip the rest of the current iteration we use next statement. When next statement is executed no
other iteration will be performed. next statement is similar as continue statement in any other
language.
Syntax:
next
Example :
# Ruby program of using next statement
#!/usr/bin/ruby -w
for x in 0..6
# Used condition
if x+1 < 4 then
# Printing values
puts "Value of x is : #{x}"
end
Output :
Value of x is : 3
Value of x is : 4
Value of x is : 5
Value of x is : 6
Conditional statements are also known by the name of conditional processing or conditional
expressions. They are used to perform a certain set of instructions if a specified condition is met. The
conditions are generally of Boolean type and return either true or false as the result. Conditionals are
formed using if or case with some comparison operators. A conditional assists data about where to move
next. In Ruby, 0 is considered as true whereas in other programming languages it is considered false.
Following are the basic type of conditional statements which are supported by Ruby:
1. If statement
2. If else statement
3. short if statement
4. If else if statement
5. Unless
6. Case statement
1) if statement
It is the most basic type of branching statement you get to know during programing. In the simpler words,
it means if you find this true, do something, and otherwise do something else. They are quite easy to write.
Syntax:
if (condition)
#statements
end
Example:
if age.to_i >= 18
puts "You are allowed to vote."
end
Output
First run:
Enter your age
23
You are allowed to vote.
Second run:
Enter your age
12
2) if else statement
if else statement is used to indicate what should happen next if the condition fails to be satisfied. It comes
with an additional 'else' with it.
Syntax:
if (condition)
#instructions
else
#instructions
end
In the above, if..end example we can observe that nothing is showing to the user as the message if the
user fails to be older than 18. Let us modify that code and informs the user by using else keyword.
Example:
if age.to_i >= 18
puts "You are allowed to vote."
else
puts "You are younger than 18 years."
end
Output
First run:
Enter your age
23
You are allowed to vote.
Second run:
Enter your age
12
You are younger than 18 years.
ADVERTISEMENT
3) Short-if statement
Its functioning is very similar to if...else statement. It is a ternary operator and used for computing
result just in one line which saves space and eventually reduces the line of code. It is recommended to be
used in small tasks.
Syntax:
Example:
result = (marks>45)?'pass':'fail'
puts "#{result}"
Output
First run:
Enter marks:
67
pass
Second run:
Enter marks:
12
fail
In the above example, you have observed that we can compute the result in a single line and we are storing
the result in a variable. It is also known as ?: operator.
4) if else if statement
The if-else if statement provides great help when you have more than two conditions. If the if condition is
evaluated as false then the pointer will jump to elsif condition and so on. Remember that, in syntax, it
is elsif (an else without 'e').
Syntax:
if expression
#code block.
elsif expression2
#code block.
elsif expression3
#code block.
else
#code block
end
Example:
if fruit=="banana"
puts "Outstanding Choice!"
elsif fruit=="Apple"
puts "An Apple a day, keeps the doctor away!"
elsif fruit=="Grapes"
puts "Good in taste"
else
puts "I can't get you"
end
Output
First run:
Enter fruit:
Grapes
Good in taste
Second run:
Enter fruit:
Apple
An Apple a day, keeps the doctor away!
ADVERTISEMENT
5) unless
The unless statement is a converse of if statement. If statement is evaluated when the condition turns out to
be true but in the case of unless statement, the code block it contains will only be executed when the
condition results to be false.
Syntax:
unless condition
#code block
end
Example (a):
flag = false
unless flag
puts "flag is false"
end
Output
flag is false
Example (b):
flag = true
unless flag
puts "flag is false"
end
Output
6) case statement
case statement can be interchangeably used with if..elsif..end statement. We use a keyword when for
implementing case conditionals. Case statement makes our code more readable.
Syntax:
Example:
case fruit
when "Banana"
puts "Outstanding Choice!"
when "Apple"
puts "An Apple a day, keeps the doctor away!"
when "Grapes"
puts "Good in taste"
else
puts "I can't get you"
end
Output
First run:
Enter fruit:
Banana
Outstanding Choice!
Second run:
Enter fruit:
Apple
An Apple a day, keeps the doctor away!
l O M o A R c PS D | 1 6 2 8 9 4 5 1
.
l O M oA R c P S D | 1 6 2 8 9 4 5 1
A R cP S D | 1 62 8 9 4 51
OBJECTIVES:
Recommended System/Software Requirements:
Intel based desktop PC with minimum of 2.6GHZ or faster processor with at least 256
MB RAM and 40GB free disk space.
Operating system: Flavor of any LINUX/WINDOWS.
Software: Ruby, TCL, Perl.
INTRODUCTION TO SCRIPTING LANGUAGES
Scripts and programs
Scripting is the action of typing scripts using a scripting language, distinguishing neatly between
programs,
which are written in conventional programming language such as C,C++,java, and scripts, which are
written using a different kind of language.
We could reasonably argue that the use of scripting languages is just another kind of
programming.
Scripting languages are used for is qualitatively different from conventional programming languages
like
C++ and Ada address the problem of developing large applications from the ground up, employing a
team
of professional programmers, starting from well-defined specifications, and meeting specified
performance
constraints.
Writing programs where speed of development is more important than run-time efficiency.
The most important difference is that scripting languages incorporate features that enhance the
productivity of the user in one way or another, making them accessible to people who would not
normally describe themselves as programmers, their primary employment being in some other
capacity. Scripting languages
make programmers of us all, to some extent.
Origin of scripting
The use of the word ‘script’ in a computing context dates back to the early 1970s,when the originators
of the UNIX operating system create the term ‘shell script’ for sequence of commands that were to be
read from a file and follow in sequence as if they had been typed in at the keyword. e.g. an ‘AWKscript’, a
‘perl script’ etc.. the name ‘script ‘ being used for a text file that was intended to be executed directly
rather than being compiled to a different form of file prior to execution.
S D |1 6 2 8 9 4 5 1
1. GUIDELINES TO STUDENTS
2. Students are supposed to occupy the systems allotted to them and are not supposed to talk or
make noise in the lab.
3. Students are required to carry their observation book and lab records with completed exercises
while entering the lab.
2. LAB OBJECTIVE
3. LAB OUTCOME
Able to use Scripting languages compiler and platform to write and execute scripting languages
program.
Understand and Apply Object oriented features and Scripting languages concepts.
Ability to understand the differences between Scripting languages and programming languages
There are 30 systems (HP) installed in this Lab. Their configurations are as follows:
1 Experiment1 :
Write a Ruby script to create a new string which is n copies of a given string
where n is a nonnegative integer
7
2 Experiment 2 :
8
2. Write a Ruby script which accept the radius of a circle from the user and
compute the parameter and area.
3 Experiment 3 :
3. Write a Ruby script which accept the user's first and last name and print 9
them in reverse order with a space between them
4. Experiment 4 :
4. Write a Ruby script to accept a filename from the user print the extension
of that
5 Experiment 5 :
7. Write a Ruby scirpt to check two integers and return true if one of them is 20
otherwise return their sum
11
8 Experiment 8 :
12
8. Write a Ruby script to check two temperatures and return true if one is less
than 0 and the other is greater than 100
9 Experiment 9 :
10. Write a Ruby program to retrieve the total marks where subject name and 1
marks of a student stored in a hash 6
o A R cP S D | 16 2 8 9 45 1
1. Write a Ruby script to create a new string which is n copies of a given
string where n is a nonnegative integer
Ruby Code:
def multiple_string(str, n)
return str*n
end
print multiple_string('a', 1),"\n"
print multiple_string('a', 2),"\n"
print multiple_string('a', 3),"\n"
print multiple_string('a', 4),"\n"
print multiple_string('a', 5),"\n"
Output:
a
aa
aaa
aaaa
aaaaa
M o A R c P S D |1 6 2 8 9 4 5 1
2. Write a Ruby script which accept the radius of a circle from the
user and compute the parameter and area.
Ruby Code:
Output:
Input the radius of the circle: The perimeter is 31.41592653.
The area is 78.539816325.
l O M o A R cPS D | 1 62 8 9 4 5 1
3. Write a Ruby script which accept the user's first and last name
and
print them in reverse order with a space between them
Ruby Code:
puts "Input your first name: "
fname = gets.chomp
puts "Input your last name: "
lname = gets.chomp
puts "Hello #{lname} #{fname}"
Output:
Input your first name:
Input your last name:
Hello Lanoie Gary
o A R cP S D | 16 2 8 9 45 1
# file name
fbname = File.basename file
puts "File name: "+fbname
# basename
bname = “File.basename file,".rb"
puts "Base name: "+bname
# file extention
ffextn = File.extname file
puts "Extention: "+ffextn
# path name
path_name= File.dirname file
puts "Path name: "+path_name
Output:
File name: test.rb
Base name: test
Extention: .rb
Path name: /user/system
o A R cP S D | 16 2 8 9 45 1
Ruby Code:
x,y,z = 2,5,4
if x >= y and x >= z
puts "x = #{x} is greatest."
elsif y >= z and y >= x
puts "y = #{y} is greatest."
else
puts "z = #{z} is greatest."
end
Copy
Output:
y = 5 is greatest.
l O M o A R cP S D | 1 62 8 9 4 5 1
7. Write a Ruby script to print odd numbers from 10
to 1
Ruby Code:
puts "Odd numbers between 9 to 1: "
9.step 1, -2 do |x|
puts "#{x}"
end
Output:
Odd numbers between 9 to 1:
9
7
5
3
1
o A R cP S D | 16 2 8 9 45 1
7. Write a Ruby scirpt to check two integers and return true if one of
them
is 20 otherwise return their sum
Ruby Code:
def makes20(x,y)
return x == 20 || y == 20 || x + y == 20
end
8. Write a Ruby script to check two temperatures and return true if one
is less than 0 and the other is greater than 100
Output:
true
true
false
O M o A R cP S D | 1 62 8 9 4 5 1
o A R cP S D | 16 2 8 9 45 1
10. Write a Ruby program to retrieve the total marks where subject
name and marks of a student stored in a hash
Sample subject and marks : Literature -74, Science – 89, Math-91
Ruby Code:
student_marks = Hash.new 0
student_marks['Literature'] = 74
student_marks['Science'] = 89
student_marks['Math'] = 91
total_marks = 0
student_marks.each {|key,value|
total_marks +=value
}
puts "Total Marks: "+total_marks.to_s
Copy
Output:
Total Marks: 254
A R cP S D | 1 62 8 9 4 51
c P S D | 1 6 2 89 4 5 1
o A R cP S D | 16 2 8 9 45 1