SL - Unit-V Final
SL - Unit-V Final
RUBY
RUBY
• Ruby is a pure object-oriented programming language.
• It was created in1993 by Yukihiro Matsumoto of Japan.
• Ruby has features that are similar to those of Smalltalk,
Perl, and Python.
• Perl, Python, and Smalltalk are scripting languages.
• Smalltalk is a true object-oriented language.
• Ruby, like Smalltalk, is a perfect object-oriented
language. Using Ruby syntax is much easier than using
Smalltalk syntax.
Features of Ruby
FileName : Test.rb
#!/usr/bin/ruby
$ ruby test.rb
Output:
Hello, Ruby!
Ruby Comments
2. Multiline comment :
#!/usr/bin/ruby
data = {“Ramu" => "Physics", “Ravi" => "Chemistry",
“Raju" => "Maths"}
puts data[“Ramu"]
puts data[“Ravi"]
puts data[“Raju"]
Output:
Ramu
Ravi
Reading input from the screen
• Use the variable $stdin for reading input from the screen.
• The standard input stream is held by $stdin, which is a
global variable.
CODE 1:
#!/usr/bin/ruby
inpt = $stdin.read
puts inpt
NOTE:
It keeps on reading the data, until Ctrl+W or Ctrl+D are
pressed.
CODE 2:reading data from the screen
#!/usr/bin/ruby
print "Enter your city: "
city = gets
puts "You live in #{city}"
Writing output to the screen
There are several methods available in Ruby if you want to
print an output on the screen.
Ex :
#!/usr/bin/ruby--->this is nothing but Ruby’s pathname
given as a comment
print "Jon "
print "Jasper\n"
puts "Lizzy"
puts "Luke”
NOTE:
The print and puts statements write the outputs to the
screen. The only difference is the puts method
automatically inserts a newline character at the end, while
the print statement doesn’t.
Ruby Variables
puts("add operator")
puts(10 + 20) Output:
puts("subtract operator") add operator
30
puts(35 - 15) subtract operator
puts("multiply operator") 20
puts(4 * 8) multiply operator
32
puts("division operator") division operator
puts(25 / 5) 5
puts("exponential operator") exponent operator
25
puts(5 ** 2) Modulo operator
puts("modulo operator") 1
puts(25 % 4)
Bitwise Operator
Bitwise operators work on bits operands.
Logical Operator
Logical operators work on bits operands.
Ternary Operator
Ternary operators first check whether given conditions are
true or false, then execute the condition.
Program:
#!/usr/bin/ruby Output:
Ternary operator
puts("Ternary operator") 5
puts(2<5 ? 5:2) 2
puts(5<2 ? 5:2)
Assignment Operator
Assignment operator assign a value to the operands.
Comparison Operators
Comparison operators or Relational operators are used for
comparison of two values.
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.
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.
Control statements
•A programming language uses control statements to
control the flow of execution of the program based on
certain conditions.
•These are used to cause the flow of execution to advance
and branch based on changes to the state of a program.
Decision-Making Statements in Ruby:
if statement
if-else statement
if -elsif ladder
Ternary statement
if statement
•do -while loop is similar to while loop with the only difference that it checks
the time fore condition after executing the statements, i.e it will execute the
loop body on 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 booleanExpression
end
until Loop
•Ruby until loop will executes the statements or code till the given condition
evaluates to true.
•It’s just opposite to the while loop which executes until the given condition
evaluates to false.
Syntax:
until conditional [do]
# code to be executed
end
Ruby break Statement
Syntax
break
Terminates the most internal loop. Terminates a method with an associated
block if called within the block .
break statement program
Ruby next Statement
Syntax
next
Jumps to the next iteration of the most internal loop. Terminates execution of a block if
called within a block.
Example
Ruby redo Statement
Syntax
redo
Restarts this iteration of the most internal loop, without checking loop condition.
Ruby retry Statement
Syntax:
retry
If retry appears in rescue clause of begin expression, restart from the beginning
of the begin body.
Redo vs. Retry
• redo and retry are both used to re-execute parts of a loop But they differ in
how much they re-execute:
• redo only repeats the current iteration, while retry repeats the whole loop from the start.
redo statement
Program: Output:
Value: 0
for i in 0..5 Value: 1
puts "Value: #{i}" Value: 2
redo if i > 2 Value: 3
end Value: 3
Value: 3
# ... this is an infinite loop
# only the last iteration is repeated
retry statement
Output:
Value: 0
Value: 1
Program:
Value: 2
for i in 0..5
Value: 3
puts "Value: #{i}“
Value: 0
retry if i > 2
Value: 1
end
Value: 2
Value :3
# ... this is an infinite loop, too
# the whole loop starts from the
beginning after a retry:
for syntax
Syntax:
( expression).each do |variable[, variable...]| code end
except that a for loop doesn't create a new scope for local variables.
Example
#!/usr/bin/ruby
(0..5).each do |i|
end
Ruby - Methods
• 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.
Method with parameter
Syntax:
def method_name (var1, var2)
statement1
statement2
end
If you would like to take an array of strings & join these strings
into a big string you can use the join method.
Ruby Arrays
• In Ruby, there are several ways to retrieve the elements from the
array but the most used way is to use the index of an array.
Retrieving Multiple Elements from Array
• There can be many situations where the user need to access the
multiple elements from the array. So to access the multiple elements,
pass the two specified array index into the [].
Adding Items to Array
OR
• Ruby blocks are little anonymous functions that can be passed into methods.
• A block is the same thing as a method, but it does not belong to an object
• A block is written in two ways,
1.Multi-line between do and end (multi-line blocks )
2.Inline between braces {}
Syntax:
[1, 2, 3].each { |num| puts num }
^^^^^ ^^^^^^^^
block block arguments body
# Form 2: recommended for multi-line
blocks
[1, 2, 3].each do |num|
puts num
end
The yield Statement
• The yield statement is used to call a block inside the method using
the yield keyword .
Passing parameters with yield statement
• One or more than one parameter can be passed with the yield
statement.
The BEGIN Statement
If you want a piece of code to be executed before running the main
program, place the code in a BEGIN statement.
Syntax :
BEGIN {
code
}
Example:
#!/usr/bin/ruby
puts "This is the main Program"
BEGIN {
puts "This is executed before the main program"
}
OUTPUT:
• The puts statement instructs the program to display the value stored
in the variable. This will add a new line at the end of each line it
writes.
The gets Statement
• The gets statement can be used to take any input from the user from
standard screen called STDIN.
The putc Statement
• This mode opens a file with both read and write permissions.
• This command removes all existing data in the file, and
effectively overwrites an existing file.
• If a file with the specified name does not exist, you a new file is
created.
file = File.open ('myfile.txt', 'w+’)
• This is similar to the ‘w+’ mode, with the difference that the
pointer is positioned at the end of the file. This means we
append to the file and do not overwrite it.
• If the file exists, it can be appended. If it doesn’t exist, a new
file is created.
file = File.open ('myfile.txt', 'a+')
Ruby opening a file
A Ruby file can be created using different methods for reading, writing or
both. There are two methods to open a file in Ruby:
• File.new method : Using this method a new file can be created for
reading, writing or both.
Syntax:
fileobject = File.new("fileName.rb“, “mode”)
• File.open method : Using this method a new file object is created. That
file object is assigned to a file.
Syntax:
File.open("fileName.rb", "mode") do |f|
• puts :function is a library function for writing the string to the file.
• To create a form tag with the specified action, and with POST
request use the following syntax
<%= form_tag :action => 'update', :id =>
@some_object %>
<%= text_area "post", "body", "cols" => 20, "rows" => 40%>
Example :
check_box("post", "validated")