0% found this document useful (0 votes)
11 views160 pages

SL - Unit-V Final

Uploaded by

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

SL - Unit-V Final

Uploaded by

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

UNIT –V

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

•Ruby is an open-source and is freely available on the Web.


•Ruby is a general-purpose, interpreted programming language.
•Ruby is a true object-oriented programming language.
•Ruby is a server-side scripting language similar to Python and PERL.
•Ruby can be embedded into Hypertext Markup Language (HTML).
•Ruby has a clean and easy syntax that allows a new developer to learn
very quickly and easily.
•Ruby has similar syntax to that of many programming languages such
as C++ and Perl.
•Ruby is very much scalable and big programs written in Ruby are easily
maintainable.
•Ruby can be used for developing Internet and intranet applications.
PROGRAM

FileName : Test.rb

#!/usr/bin/ruby

puts "Hello, Ruby!";

run program using

$ ruby test.rb

Output:

Hello, Ruby!
Ruby Comments

A comment hides a line, part of a line, or several


lines from the Ruby interpreter.
1. Single line comment: use the hash character (#)
at the beginning of a line
Ex:
# I am a comment. Just ignore me.

2. Multiline comment :

This block comment conceals several lines from the


interpreter with =begin/=end −
Ex : =begin
This is a comment.
This is a comment, too.
This is a comment, too.
I said that already.
=end
Ruby Data types
Data types represents a type of data such as text, string, numbers,
etc. There are different data types in Ruby:
1. Numbers
2. Strings
3. Symbols
4. Hashes
5. Arrays
6. Booleans
Numbers:
Integers and floating point numbers come in the category of
numbers.
Ex:
my_int = 3
my_flt = 3.1
puts (my_flt * my_int)
puts (my_flt + my_int)
puts (my_flt / my_int)
puts (my_int - my_flt)
Output: 9.3
6.1
1.033333
-0.1
Symbols:
Symbols are like strings. A symbol is preceded by a colon
(:). For example,
Ex: :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.
Program:
My_symbols={:ap=>”apple”, :bin=>”banana”, :mg=>”ma
ngo”}
Puts my_symbols[:ap]
Puts my_symbols[:bn]
Puts my_symbols[:mg]
Output:
Apple
Banana
Mango
NOTE:
If we use symbols in hashes no more worrying about the
quotes around the values and the keys.
Strings:
A string is made up of multiple characters.
They are defined by enclosing a set of characters within
single (‘x’) or double (“x”) quotes.
EX:
puts “Hello World !”
Booleans:
The Boolean data type represents only one bit of
information that says whether the value is true or false.
A value of this data type is returned when two values are
compared.
Program:
my_str_1 = "Hello"
my_str_2 = "World"
if my_str_1 == my_str_2
puts "It is True!"
else
puts "It is False!"
end
Output:
It is False!
Arrays:
• An array can store multiple data items of all types.
• Items in an array are separated by a comma in-between them and
enclosed within square brackets.
• The first item of the array has an index of 0.
Code:
#!/usr/bin/ruby
data = [“Ram", “Ravi", “Raja"]
puts data[0]
puts data[1]
puts data[2]
Output: ruby arr.rb
Ram
Ravi
Raja
Hashes:
• A hash assign 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.
Ex:

#!/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

• A variable is simply a name for a value. Variables are


created and values assigned to them by assignment
expressions.
• There are four types of variables in Ruby:
1.Local variables
2.Class variables
3.Instance variables
4.Global variables
Variable
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. If
no method by that name exists, Ruby raises a
NameError.
EX:
print a # Prints nil: the variable exists but is not
assigned
print b # NameError: no variable or method
named b exists
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 descendents 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.
• An uninitialized instance variable will have a nil value.
Global variables

• A global variable name starts with a $ sign.


• Its scope is globally, means it can be accessed from any
where in a program.
• An uninitialized global variable will have a nil value.
• There are a number of predefined global variables in
Ruby.
Ruby Operators

• An operator is a symbol that represents an operation to


be performed with one or more operand.
• Operators are the foundation of any programming
language. Operators allow us to perform different kinds
of operations on operands.
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
Program:
#!/usr/bin/ruby
Output: ruby file.rb
puts("Unary operator") Unary operator
puts(~5) -6
puts(~-5) 4
puts(!true) false
puts(!false) true
Arithmetic Operator
Arithmetic operators take numerical values as operands
and return them in a single value.
#!/usr/bin/ruby

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

If statement in Ruby is used to decide whether a certain


statement or block of statements will be executed or not i.e
if a certain condition is true then a block of statement is
executed otherwise not.
Syntax:
If condition
# statements to be executed
end
if – else Statement
•In this ‘if’ statement used to execute block of code when
the condition is true and ‘else’ statement is used to execute
a block of code when the condition is false.
Syntax:
if condition
# code if the condition is true
else
# code if the condition is false
end
program
If – elsif – else ladder Statement
•A user can decide among multiple options.
•‘if’ statements are executed from the top down. As soon as one of the
conditions controlling the ‘if’ is true, the statement associated with that
‘if’ is executed, and the rest of the ladder is bypassed.
• If none of the conditions is true, then the final else statement will be
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
Ternary Statement
In Ruby ternary statement is also termed as the shortened if
statement. It will first evaluate the expression for true or
false value and then execute one of the statements. If the
expression is true, then the true statement is executed else
false statement will get executed.
Syntax:
test-expression ? if-true-expression : if-false-expression
The case statement is a multiway branch statement just like
a switch statement in other languages. It provides an easy
way to forward execution to different parts of code based
on the value of the expression.
There are 3 important keywords which are used in the case
statement:
case: It is similar to the switch keyword in another
programming languages. It takes the variables that will be
used by when keyword.
when: It is similar to the case keyword in another
programming languages. It is used to match a single
condition. There can be multiple when statements into a
single case statement.
else: It is similar to the default keyword in another
programming languages. It is optional and will execute
when nothing matches.
end
Syntax:
case expression
when expression 1
# your code
when expression 2
# your code . .
else
# your code
end
loops
•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 :
1.while loop
2. for loop
3.do..while loop
4.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.
• Basically, while loop is used when the number of iterations is not
fixed in a program.
Syntax:
while conditional [do]
# code to be executed
end
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:
for variable_name[, variable...] in expression [do]
# 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 used 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.
do..while Loop

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

puts "Value of local variable is #{i}"

end
Ruby - Methods

• Ruby methods are very similar to functions in any other programming


language.
• Ruby methods are used to bundle one or more repeatable statements
into a single unit.
• Method names should begin with a lowercase letter.
• If you begin a method name with an uppercase letter, Ruby might
think that it is a constant and hence can parse the call incorrectly.
• Methods should be defined before calling them, otherwise Ruby will
raise an Exception for undefined method invoking.
Syntax:
def method_name
#statement1
#statement2
end
Defining Method

• 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

You can set default values for the


parameter
Syntax:
def method_name (var1 = value1, var2 = value2)
statement1
statement2
end
Method with parameters
Method with default parameter
Variable Number of Parameters:

• Ruby allows the programmer to define a


method that can take the variable number of
arguments.
• It is useful when the user doesn’t know the
number of parameters to be passed while
defining the method.
Syntax:
def method_name(*variable_name)
# Statement 1
# Statement 2
.
.
end
Return statement in Methods:

• Return statement used to returns one or more values.


• By default, a method always returns the last statement
that was evaluated in the body of the method.
• ‘return’ keyword is used to return the statements.
Method with parameters and return value
Method returns multiple values
Ruby strings

• In Ruby, string is a sequence of one or more characters.


• It may consist of numbers, letters, or symbols.
• Here strings are the objects, and apart from other
languages, strings are mutable, i.e. strings can be
changed in place instead of creating new strings.
• String’s object holds and manipulates an arbitrary
sequence of the bytes that commonly represents a
sequence of characters.
• Creating Strings: To create the string, just put the
sequence of characters either in double quotes or single
quotes.
• In Ruby, there is no need to specify the data type of the
variable.
Difference between using single and double quotes
String Built-in Methods

• We need to have an instance of String object to call a String method.


• Following is the way to create an instance of String object −
new [String.new(str = "")]
• This will return a new string object containing a copy of str.
• Now, using str object, we can all use any available instance methods.
A cesin g strin g elm en ts

• Ruby string elements can be accessed in different parts


with the
help of square brackets []. Within square brackets
write the index or string.
Concatenating Strings

Ruby concatenating string implies creating one string from


multiple strings.
There are four ways to concatenate Ruby strings into single
string:
•Using plus sign in between strings.
•Using a single space in between strings.
•Using << sign in between strings.
•Using concat method in between strings.
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
Comparing Strings
Ruby strings can be compared with three operators:
•With == operator : Returns true or false
•With eql? Operator : Returns true or false
•With casecmp method : Returns 0 if matched or 1 if not
matched
Find Out If a String Contains Another String
The include? method:
Index() method
Convert a String Into An Integer
• If you want to convert a string like "49" into the Integer 49 you can use
the to_i method
• If you try this with a string that contains no numbers then you will get 0
Convert an Array to a String

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

• An array is a collection of different or similar items, stored at


contiguous memory locations.
• Store multiple items of the same type together which can be referred
to by a common name.
• An array is created by listing the elements which will be separated
by commas and enclosed between the square brackets[].
Example:
[“RAMU", 34, 45, “RAJU"]
• Array positive index starts from 0. The negative index always starts
with -1 which represents the elements from the end of the array
Creation of array in Ruby
• There are several ways to create an array. But there are two ways
which mostly used are as follows:
1.Using the new class method:
 new is a method which can be used to create the arrays with the help
of dot operator.
 Here Passing arguments to method means to provide the size to
array and elements to array.
Syntax:
name_of_array= Array.new
Example:
arr = Array.new
Here arr is the name of the array. Here Array is the class name
which is predefined in the Ruby library and new is the predefined
method.
Assign a value to each element in the array as
follows
2.Array creation Using literal constructor[]

• In Ruby, [] is known as the literal constructor which can be used to


create the arrays. Between [], different or similar type values can be
assigned to an array.

Retrieving Or Accessing Elements from Array

• 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

Ruby array elements can be added in different ways.


• push or << :Using push or <<, items can be added at the end of
an array.
• Unshift :Using unshift, a new element can be added at the
beginning of an array.
• 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.
Removing Items from Array

Ruby array elements can be removed in different ways.


• pop: items can be removed from the end of an array. It returns
the removed item.
• shift: items can be removed from the start of an array. It
returns the removed item.
• delete : items can be removed from anywhere in an array. It
returns the removed item.
• uniq : duplicate elements can be removed from an array. It
returns the remaining array.
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.
• If a hash is accessed with a key that does not exist, the method will
return nil.
Creating Hashes:
• Ruby hash is created by writing key-value pair within {} curly
braces.
• To fetch a hash value, write the required key within [] square
bracket.
Syntax:

name = {"key1" => "value1", "key2" => "value2",


"key3" => "value3”…..}

OR

name = {key1: 'value1', key2: 'value2', key3: 'value3'...}


 Element Assignment Associates the value given by value with
the key given by key.
h = { "a" => 100, "b" => 200 }
h["a"] = 9
h["c"] = 4
puts h
Output: {"a"=>9, "b"=>200, "c"=>4}

 [] : It is known as Element Reference. It retrieves the value that


stored in the key. If it does not find any value then it return the
default value.
syntax: hash[key]
 clear :Removes all key-value pairs from hash.
h = { "a" => 100, "b" => 200 }
h.clear # => {}
Ruby Module

• A Module is a collection of methods, constants, and class variables.


Modules are defined as a class, but with the module keyword not
with class keyword.
Important Points about Modules:
• You cannot inherit modules or you can’t create a subclass of a
module.
• Objects cannot be created from a module.
• Modules are used as namespaces and as mixins(In Ruby, a code
wrapped up in a module is called mixins).
• All the classes are modules, but all the modules are not classes.
• The name of a module must start with a capital letter.
What is module method vs instance method?
• The methods in a module may be instance methods or module
methods. Instance methods appear as methods in a class when
the module is included, module methods do not. Conversely,
module methods may be called without creating an encapsulating
object, while instance methods may not.
• Name space :A namespace is a container for multiple items which
includes classes, constants, other modules, and more. It is ensured in
a namespace that all the objects have unique names for easy
identification
• Mixins : In Ruby, a code wrapped up in a module is called mixins.
Syntax:
module Module_name
# statements to be executed
end
 To define module method user have to prefix the name of the module
with the method name while defining the method. The benefit of
defining module method is that user can call this method by simply
using the name of module and dot operator.
 A user can access the value of a module constant by using the double
colon operator(::).
 If the user will define a method with def keyword only inside a module
i.e. def method_name then it will consider as an instance method. A
user cannot access instance method directly with the use of the dot
operator as he cannot make the instance of the module.
 To access the instance method defined inside the module, the user
has to include the module inside a class and then use the class instance
to access that method.
 The user can use the module inside the class by using include
keyword.
Use of Modules:
• A module is a way categorize the methods and constants so that
user can reuse them.
• Suppose you wants to write two methods and also want to use these
methods in multiple programs. So, write these methods in a module,
so that you can easily call this module in any program with the help
of require keyword without re-writing code.
Ruby Blocks

• 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 {}

• The argument names are defined between two pipe | characters.


There are some important points about Blocks in Ruby:
•Block can accept arguments and returns a value.
•Block does not have their own name.
•Block consist of chunks of code.
•A block is always invoked with a function or can say
passed to a method call.
•To call a block within a method with a value, yield
statement is used.
# Form 1: recommended for single line blocks

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:

This is executed before the main program


This is the main Program
The END Statement

If you want a code to be executed at the end of a


program, you can use the ‘END’ statement for
specifying the code.
Syntax:
END {
block of code
}
PROGRAM
#!/usr/bin/ruby
puts "This is the main Program"
END {
puts "This is executed at the end"
}
BEGIN {
puts "This is executed before the main program"
}
OUTPUT:
This is executed before the main program
This is the main Program
This is executed at the end
Ampersand parameter (&block)

• The &block is a way to pass a reference (instead of a local variable)


to the block to a method.
• Here, block word after the & is just a name for the reference, any
other name can be used instead of this.
• Here, the block variable inside method met is a reference to the
block. It is executed with the call method. The call method is same
as yield method.
Ruby I/O

• Ruby I/O is a way to interact with your system.


• Data is sent in the form of bytes/characters.
• IO class is the basis for all input and output in Ruby.
• IO has a subclass as File class which allows reading and writing
files in Ruby. The two classes are closely associated.
• IO object represent readable/writable interactions to keyboards and
screens.
The puts Statement

• 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

• The putc statement can be used to output one character at a time.


The print Statement

• The print statement is similar to the puts statement. The only


difference is that the puts statement goes to the next line after
printing the contents, whereas with the print statement the cursor is
positioned on the same line.
Ruby File I/O
Opening a File using Different Modes in Ruby

• Ruby allows us to open a file with different permissions (modes).


• You can open a file in a read only mode, write only mode, or a read-
write mode,
syntax :
file = File.open (“filename.txt”, “mode”)
If mode is not specified, it will default to a read-only mode.
Read Only :
• Read only permission is denoted by ‘r’.
• The read only mode is the default mode.
• The file pointer points to the beginning of the file, by default.
• If you open a file as read only, you cannot edit it or change it in any
way.
file = File.open ('myfile.txt', 'r’)
Write Only :
• Write only permission is denoted by ‘w’.
• This mode should be used when you only want to add data or rather
write into a file.
• If you set a file to write only, you will not be able to read back from
it.
• The file pointer starts at the beginning of the file.
• The file, if it exists, is overwritten. Otherwise, a new file is created.
file = File.open ('myfile.txt', 'w')
Append only

• Append only permission is denoted by ‘a’.


• The main difference from the w option is that the file pointer starts at the
end of the file. This means the existing data in the file is not overwritten.
We can only add on to it.
• If the file doesn’t exist, a new file is created.
file = File.open ('myfile.txt', 'a’)

Read- write permission ‘r+’

• Read- write permission is denoted by ‘r+’.


• You can both read and modify a file with this.
• The file pointer starts at the beginning of the file by default, enabling you
to start reading from the very beginning.
file = File.open ('myfile.txt', 'r+')
Read-write permission ‘w+’

• 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+’)

Read and write permission ‘a+’

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

• Difference between both the methods is that File.open method can be


associated with a block while File.new method can't.
File.open()
Writing to the file

• puts :function is a library function for writing the string to the file.

• Syswrite():With the help of syswrite method, you can write content


into a file.
• File needs to be opened in write mode for this method. The new
content will over write the old content in an already existing file.
• putc :function is a library function for writing the character to the
file.
Reading a file

There are three different methods to read a file.


1. fileobject.sysread(number of characters ) – Return only
the first n characters from that file
2. fileobject.read – Return the entire content from a file
3. fileobject.readlines – Return the values as an array of
lines
1.sysread Method
The sysread method is also used to read the content of a
file. With the help of this method you can open a file in any
mode. It will print till n characters mentioned in sysread method
from the file.
sysread() and read()
Readlines method
• Renaming and Deleting a file
Ruby files are renamed using rename method and deleted using
delete method.
• File Inquiries
To check whether the file exists or not
Form handling in Ruby

• form is a section of a document which contains controls such as text fields,


password fields, checkboxes, radio buttons, submit button, menus etc.
• forms are required if you want to collect some data from of the site visitor.
• The collected data can be validated on the client browser with JavaScript
programming language. After validation of form data on the client-side, the
user clicks on the Submit button in the form. After this, data is sent to the
server for further processing.
• For example: If a user want to purchase some items on internet, he/she must fill
the form such as shipping address and credit/debit card details so that item can
be sent to the given address.
• element represents a document section
containing
interactive controls for submitting information.
Form

• To create a form tag with the specified action, and with POST
request use the following syntax
<%= form_tag :action => 'update', :id =>
@some_object %>

<%= form_tag( { :action => :save, }, { :method


=> :post }) %>
Text Fields

To create a text field use the following syntax

<%= text_field :modelname, :attribute_name, options %>


Ex:
<%= text_field "person", "name", "size" => 20 %>

This will generate following code −

<input type = "text" id = "person_name" name = "person[name]" size =


"20" value = "<%= @person.name %>" />
To create hidden fields, use the following syntax;
<%= hidden_field ... %>
To create password fields, use the following syntax;
<%= password_field ... %>
To create file upload fields, use the following syntax;
<%= file_field ... %>
text area

To create a text area, use the following syntax −


<%= text_area ... %>
Have a look at the following example −

<%= text_area "post", "body", "cols" => 20, "rows" => 40%>

This will generate the following code −

<textarea cols = "20" rows = "40" id = "post_body" name ="


post[body]"> %={@post.body}%
</textarea>
Checkbox Button

To create a Checkbox Button use the following syntax −


<%= check_box :modelname, :attribute,options,on_value,off_value%>

Example :

check_box("post", "validated")

This will generate the following code −

<input type = "checkbox" id = "post_validate" name =


"post[validated]" value = "1" checked = "checked" />
<input name = "post[validated]" type = "hidden" value = "0" />
check_box("puppy", "gooddog", {}, "yes", "no")

This will generate following code −

<input type = "checkbox" id = "puppy_gooddog" name =


"puppy[gooddog]" value = "yes" />
<input name = "puppy[gooddog]" type = "hidden" value = "no" />
dropdown
To create a dropdown list, use the following syntax

<%= select :variable,:attribute,choices,options,html_options%>


select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] })

This could generate the following code. It depends on what value is


available in your database.

<select name = "post[person_id]">


<option value = "1">David</option>
<option value = "2">Sam</option>
<option value = "3">Tobias</option>
</select>
End Form Tag

Use following syntax to create </form> tag

<%= end_form_tag %>

You might also like