AWT_Module 2(Ruby)
AWT_Module 2(Ruby)
Module 3
Introductionto Ruby and Introduction to Rails
Scalars
There are two categories of scalar types – Numeric Literals and String Literals
Numeric Literals
All Numeric data types in Ruby are descendants of the Numeric class.
The immediate child classes of Numeric are Integer and Float.
The integer class has two child classes – Fixnum object and Bignum object.
The Integer literal that fits into the range of a machine word, which is often 32 bits, is a Fixnum object.
An Integer literal that is outside the Fixnum object range is a Bignum object.
If a Fixnum integer grows beyond size limitation of Fixnum object, it is coerced to Bignum object.
If an operation on a Bignum object results in a value that fits in a Fixnum object, it is coerced to a
Fixnum object.
Underscore characters can appear embedded in integer literals. Ruby ignores such underscores.
Example: instead of 124761325, can be used as 124_761_325.
The decimal point must be embedded, that is, it must be both preceded and followed by at least one
digit. Example: 0.1 is legal but .1 is not a legal literal.
Ruby does not required to use semicolon at the each statement end of the line.
String Literals
All string literals are String objects, which are sequence of bytes that represent characters.
Strings can be represent either in single-quotes or double-quotes.
The null string (one with no characters) can be denoted with either ' ' or " ".
1
Module 2 [20MCA41] Advances in Web Technologies
Numeric Operators
Binary Operators:
Binary operators are + for addition, - for subtraction, * for multiplication, / for division, ** for
exponentiation, and % for modulus.
Ruby does not include the increment (++) and decrement (--) operator.
Ruby includes the Math module, which has methods for basic trigonometric functions. Such as
Math.cos(x), Math.sin(x), Math.log(x), Math.sqrt(x), and Math.tan(x). where x is a parameter to be
passed.
Ruby have interactive interpreter. It allows one to type any ruby expression and get immediate response
from the interpreter.
The interactive interpreter’s name is Interactive Ruby. Whose acronym, irb is the name of the program
that supports it.
Simply typing irb at the command prompt in the directory that contains the ruby interpreter.
Example: irb
irb will response with its own prompt, which is: irb(main):001:0>
At this prompt, any Ruby expression or statement can be typed. irb interprets the expression or
statement and returns the value after an implication symbol(=>).
2
Module 2 [20MCA41] Advances in Web Technologies
Example:
irb(main):001:0> 17 * 3
=> 51
irb(main):001:0>
The default prompt can be changed with the following command
irb(main):001:0> conf.prompt_i = ">>"
Now the new prompt is: >>
String Methods
The ruby String class has more than 75 methods, a few of which are:
Catenation method (+)
Assignment method
<< method
Chr method
Substring method
== method
equal? method
eql? method
< = > compare method
The other most commonly used methods are
Method Action
capitalize Convert the first letter to uppercase and the rest of the letters to lowercase
chop Removes the last character
chomp Removes a newline from the right end, if there is one
upcase Converts all lowercase to uppercase
downcase Converts all uppercase to lowercase
strip Removes the spaces on both ends
lstrip Removes the spaces on the left end
rstrip Removes the spaces on the right end
reverse Reverse the characters of the string
swapcase Convert all uppercase letters to lowercase and all lowercase letters to uppercase
Catenation method
The String method for catenation is specified by plus (+), which can be used as binaryoperator.
Example: >> "Happy" + "" + "Morning"
=> "Happy Morning"
Assignment method
Example: >> a = "Happy"
=> "Happy"
>> b = a
=> "Happy"
>> b
=> "Happy"
3
Module 2 [20MCA41] Advances in Web Technologies
<< method
To append a string to the right end of another string, use the << method.
Example: >> a = "Happy"
=> "Happy"
>> a << "Morning"
=> "Happy Morning"
Chr method
Ruby strings can be indexed, the indices begin at zero. The brackets of this method specify a getter method
The catch with this getter method is that it returns the ASCII code rather than the character.
To get the character, the chr method must be used.
Example:
>> be="civil" >> be="civil"
=> "civil" => "civil“
>> be[2] >> be[2].chr
=> 118 => "v"
Substring method
A multicharacter substring of a string can be accessed by including two numbers in the brackets
Example:
>> city="bangalore" >> name="Donald"
=> "bangalore" => "Donald"
>> city[3,3] >> name[3,3]="nie"
=> "gal" => "nie"
>> name
=> "Donnie"
== method
The usual way to compare strings for equality is to use the == method as an operator.
Example: >>"CITECH"=="CITECH"
=> true
>>"CITECH"=="bms"
=> false
< = > compare method
It returns -1 if the second operand is greater than the first
0, if they are equal
1, if the first operand is greater than second
Greater in this case means it belongs later in alphabetical order.
Example: >>"apple"<=>"grape"
=> -1
>>"grape"<=>"grape"
=> 0
>>"grape"<=>"apple"
=> 1
4
Module 2 [20MCA41] Advances in Web Technologies
Example of capitalize
>>str="MCA"
=> "MCA"
>>str.capitalize
=> "Mca"
Example of chomp:
>>strg="mca\n"
=> "mca\n"
>>strg.chomp
=> "mca"
Example of strip:
>>CITECH=" hello "
=> " hello "
>>CITECH.strip
=> "hello"
Example of lstrip:
>>CITECH=" hello "
=> " hello "
>>CITECH.lstrip
=> "hello "
Example of reverse:
>>CITECH=" hello "
=> " hello "
5
Module 2 [20MCA41] Advances in Web Technologies
>>CITECH.reverse
=> " olleh "
Example of swapcase:
>>cit="RaVi"
=> "RaVi"
>>cit.swapcase
=> "rAvI"
Screen Output
Output is directed to the screen with the puts method (or operator).
Example: >>name="Rohit"
=> "Rohit"
>>puts "my name is #{name}"
my name is Rohit
=> nil
The value returned by puts is nil, and that value is returned after the string has been displayed.
Keyboard Input:
The gets method gets a line of input from the keyboard, default it will be taken as string.
Example: >>fruit=gets
mango
=> "mango\n"
If a number is to be input from the keyboard, the string from gets must be converted to an integer with to_i
method.
If the number is a floating-point value, the conversion method is to_f.
Example: >> age=gets.to_i
23
=> 23
>> age=gets.to_f
23.5
=> 23.5
Control Statements
Relational Operators
Operator Operation
== Is equal to
!= Is not equal to
< Is less than
> Is greater than
<= Is less than or equal to
>= Is greater than or equal
<=> Compare, returning -1, 0, or +1
6
Module 2 [20MCA41] Advances in Web Technologies
The Ruby while and for statements are similar to those of C and its descendants.
The bodies of both are sequences of statements that end with end.
Syntax: while control expression
loop body statement(s)
end
The until statement is similar to the while statement except that the inverse of the value of the control
expression is used.
7
Module 2 [20MCA41] Advances in Web Technologies
sum = 0
loop
begin
dat = gets.to_i
if dat < 0 next
sum += dat
end
8
Module 2 [20MCA41] Advances in Web Technologies
Fundamentals of Arrays
Arrays in Ruby are more flexible than those of most of the other common languages.
There are two differences between Ruby arrays and other languages such as C, C++, and java.
First, the length of the Ruby array is dynamic. It can grow and shrink any time during program
execution.
Second, Array can store different types of data.
Ruby arrays can be created in two different ways.
First, an array can be created by sending the new message to the predefined Array class, including a
parameter for the size of the array.
Second, an array created with the new method can also be initialized by including a second parameter,
but every element is given the same value.
Example: >>list1=Array.new(5)
=> [nil, nil, nil, nil, nil]
Example: >>list3=Array.new(3,"cit")
=> ["cit", "cit", "cit"]
The length of an array can be retrieved with the length method.
Example: >>list3.length
=> 3
All Ruby array elements use integers as subscripts, and the lower-bound subscript of every array is zero.
Example: >> ruby = [2,4,6,8,9]
=> [2, 4, 6, 8, 9]
>> ada = ruby[2]
=> 6
>> ruby[3] = 10
=> 10
>> ruby
=> [2, 4, 6, 10, 9]
9
Module 2 [20MCA41] Advances in Web Technologies
shift method removes and returns the first element of the array.
Example: >> ruby = [2,3,4,5,6]
=> [2, 3, 4, 5, 6]
>> first = ruby.shift
=> 2
>> ruby
=> [3, 4, 5, 6]
unshift method takes a scalar or an array literal as a parameter. The scalar or array literal is append to the
beginning of the array.
Example: >> ruby
=> [3, 4, 5, 6]
>> ruby.unshift ("mca","be")
=> ["mca", "be", 3, 4, 5, 6]
pop method removes and returns last element from the array.
push method also takes scalar or an array literal. The scalar or an array literal is added to the high end of
the array.
Example: >> ruby
=> ["mca", "be", 3, 4, 5, 6]
>> ruby.push(100,60)
=> ["mca", "be", 3, 4, 5, 6, 100, 60]
10
Module 2 [20MCA41] Advances in Web Technologies
include?: The include? predicate method searches an array for a specific object.
Example: >> cit2
=> [6, 8, 7]
>> cit2.include?(6)
=> true
Set operations
There are three methods that form perform set operations on two arrays.
& for set intersection
- for set difference
| for set union.
Example: >> set1 = [2,4,6,8]
=> [2,4,6,8]
>> set2 = [4,6,8,10]
=> [4,6,8,10]
>> set1 & set2
=> [4,6,8]
>> set1 - set2
=> [2]
>> set1 | set2
=> [2,4,6,8,10]
11
Module 2 [20MCA41] Advances in Web Technologies
Hashes
Associative arrays are arrays in which each data element is paired with a key, which is used to identify
the data element.
The two difference between arrays and hashes are:
First, arrays use numeric subscripts to address specific elements whereas hashes us keys to address
elements.
Second, the elements in arrays are ordered by subscripts but the elements in hashes are not.
Like arrays, hashes can be created in two ways, with the new method or by assigning a literal to a
variable.
Example: >> ages={"ravi"=>23,"raj"=>34,"kiran"=>12}
=> {"kiran"=>12, "raj"=>34, "ravi"=>23}
If the new method is sent to the Hash class without a parameter, it creates an empty hash.
Example: >> college = Hash.new{}
An individual value element of a hash can be referenced by subscripting the hash name with the key.
Example: >> ages = {"ravi"=>23,"raj"=>34,"kiran"=>12}
=> {"kiran"=>12, "raj"=>34, "ravi"=>23}
>> ages["ravi"]
=> 23
New values are added to a hash by assigning the value of the new element to a reference to the key of
the new element.
Example: >> ages = {"ravi"=>23,"raj"=>34,"kiran"=>12}
>> ages["mohan"]=33
>> ages
=> {"kiran"=>12, "raj"=>34, "ravi"=>23, mohan"=>33}
An element can be removed from a hash with the delete method, which takes an element key as a
parameter.
Example: >> ages
=> {"kiran"=>12, "raj"=>34, "ravi"=>23, mohan"=>33}
>> ages.delete("raj")
=> 34
>> ages
=> {"kiran"=>12, "ravi"=>23, "mohan"=>33}
A hash can be set to empty in two ways:
First, an empty hash literal can be assigned to the hash.
Example: >> ages={}
=> {}
Second, the clear method can be used on the hash.
Example: >> ages.clear
=> {}
12
Module 2 [20MCA41] Advances in Web Technologies
has_key?
Predicate method is used to determine whether an element with the specific key is in a hash.
Example: >> ages.has_key?(“ravi”)
=> true
keys and values
Hash can be extracted into arrays with the methods keys and values.
Example: >> CITECH={"mca"=>12,"mba"=>10,"puc"=>6}
=> {"mca"=>12, "mba"=>10, "puc"=>6}
>> CITECH.keys
=> ["mca", "mba", "puc"]
>> CITECH.values
=> [12, 10, 6]
Methods
A method definition includes the method’s header and a sequence of statements, ending with the end
reserved word, which describes its actions.
A method header is the reserved word def, the method’s name, and optionally a parenthesized list of
formal parameters.
Method name must begin with lowercase letters.
If the method has no parameters, the parentheses are omitted it means no parentheses.
Syntax: def method_name
statements….
end
You can represent a method that accepts parameters like this:
Syntax: def method_name (var1, var2)
Statements.....
end
You can set default values for the parameters which will be used if method is called without passing
required parameters:
Syntax: def method_name (var1=value1, var2=value2)
statements….
end
Example: #!/usr/bin/ruby
def test(a1="Ruby", a2="Perl")
puts "The programming language is #{a1}"
puts "The programming language is #{a2}"
end
13
Module 2 [20MCA41] Advances in Web Technologies
Local variables
Local variables are either formal parameters or are variables created in a method.
The scope of the local variable is from the header of the method to the end of the method.
Local variables must be begin with either a lowercase letter or an underscore ( _ ).
Beyond the first character, local variable names can have any number of letters, digits, or underscores.
The lifetime of the local variable is from the time it is created until end of the execution of the method.
The return statement in ruby is used to return one or more values from a Ruby Method.
Example: #!/usr/bin/ruby
def test
i = 100
j = 200
k =300
return i+j+k
end
var = test
puts var
Parameters:
In Ruby, parameters transmission of scalars is strictly one-way into the method.
The value of the scalar actual parameters are available to the method through its formal parameters.
Example: def swap(x,y)
t=x
x=y
y=t
puts "the values are #{x},#{y}"
end
a=1
b=2
swap(a,b)
Classes
Classes in Ruby are like those of other object-oriented programming languages.
A class is the blueprint from which individual objects are created.
Defining a Class in Ruby:
A class in Ruby always starts with the keyword class followed by the name of the class.
The name should always be in initial capitals.
Syntax class Customer
.....
end
14
Module 2 [20MCA41] Advances in Web Technologies
Example: #!/usr/bin/ruby
class Sample
def mca
puts "Hello Ruby!"
end
end
CITECH = Sample.
newCITECH.mca
15
Module 2 [20MCA41] Advances in Web Technologies
Access Control:
Access control in Ruby is different for access to data than it is for access to methods.
All instance data has private access by default, and it cannot be changed,
If external access to an instance variable is required, access methods must be changed.
Example: class My_class
def initialize
@one = 1
@two = 2
# A getter for @one
def one
@one
end
# A setter for @one
def one = (my_one)
@one = my_one
end
end
The equal sign (=) attached to the name of the setter method means that the method is assignable. So, all
setter methods have equal signs attached to their names.
Ruby provides shortcuts for getter and setter methods. Those are attr_reader and attr-
writer.
attr_reader (getter) is actually method call, using the symbols :one and :two as the actual
parameters.
Example: attr_reader : one, :two
attr-writer (setter)as similarly creates setter method.
The three levels of access control for methods are defined as follows,
public: access means the method can be called by any code.
protected: access means that only objects of the defining class and its subclasses may call the
method.
private: that the method cannot be called with an explicit receiver object. Because the default
receiver object is self, a private method, can only be called in the context of the current object.
Example: class My_class
def meth1
....
end
....
16
Module 2 [20MCA41] Advances in Web Technologies
private
def meth7
....
end
....
protected
def meth11
....
end
....
end
Inheritance:
Subclasses are defined in Ruby using < symbol.
Syntax: class My_subclass < Base_class
times iterator
The times iterator method provides a way to build counting loops. The times method repeatedly
executes the block.
Example: 3.times {puts "hello"}
hello
hello
hello
=> 3
17
Module 3 [16MCA42] Advanced Web Programming
each iterator
The most commonly used iterator is each, which is often used to go through arrays and apply a block to
each element.
Blocks can have parameters, which appear at the beginning of the block, delimited by vertical bars ( | ).
Example: >> list10 = [1, 2, 4, 5]
=> [1, 2, 4, 5]
>> list10.each {|value| puts value}
1
2
4
5
=> [1, 2, 4, 5]
upto iterator
The upto iterator method is used like times, except that the last value of the counter is given as a
parameter.
Example: >> 4.upto (10) {|value| puts value}
4
5
6
7
8
9
10
step iterator
The step iterator method takes a terminal value and step size as parameters and generated the value from
that of the object to which it is sent and the terminal value.
Example: >> 2.step (8,1) {|value| puts value}
2
3
4
5
6
7
8
collect iterator
The collect iterator method takes the elements from an array, one at a time, like each, and puts the value
generated by the given block into a new array.
Example: >> list15 = [5,10,15,20]
=> [5, 10, 15, 20]
>> list15.collect {|value |value = value-5}
=> [0, 5, 10, 15]
MCA, 18
CITECH
Module 3 [16MCA42] Advanced Web Programming
Pattern matching
The basics of Pattern matching:
In Ruby, the pattern-matching operation is specified with the matching operators, =~.
Patterns are placed between slashes ( / / ).
Example: >> pattern = "good morning"
=> "good morning"
>> pattern =~ /g/
=> 0
>> pattern =~ /r/
=> 7
>> pattern =~ /z/
=> nil
Remembering matches:
The part of the string that matched a part of the pattern can be saved in an implicit variable for later use.
Example: >> date="24 april 2015"
=> "24 april 2015"
>> date =~ /(\d+) (\w+) (\d+)/
=> 0
>> puts "#{$2} #{$1},#{$3}"
april 24,2015
Substitutions:
Sometimes the substring of a string that matched a pattern must be replaced by another string.
The substitute method, sub, takes two parameters, a pattern and a string.
Example: >> str = "we belongs to CITECH family. CITECH"
=> "we belongs to CITECH family. CITECH"
>> str.sub(/CITECH/,"cit")
=> "we belongs to cit family. CITECH"
gsub method
The gsub method is similar to sub, but finds all substring matches and replaces all of them with its
second parameter.
Example: >> str
=> "we belongs to CITECH family. CITECH"
>> str.gsub (/CITECH/,"cit")
=> "we belongs to cit family. cit"
i modifier
The i modifier, which tells the pattern matcher to ignore the case of letters.
Example: >> strg = "Is it Rose, rose, or ROSE?"
=> "Is it Rose, rose, or ROSE?"
>> strg.gsub(/Rose/i, "rose")
=> "Is it rose, rose, or rose?"
MCA, 19
CITECH