Ruby Programming Essentials Guide
Ruby Programming Essentials Guide
Ruby was designed in Japan by Yukihiro Matsumoto (Matz) and was released in 1996.
It started as a replacement for the languages like Perl and Python.
Ruby is an open-source and is freely available on the Web.
Ruby is a general-purpose, interpreted programming language.
general-purpose programming language is a programming language dedicated to a
general-purpose, where the user can writing software in a wide variety of application
domains.
Ruby is a true object-oriented programming language.
Object-oriented programming is a programming paradigm based on the concept of
"objects", which can contain data and code: data in the form of fields, and code, in the
form of procedures.
Ruby is a server-side scripting language similar to Python and PERL.
Ruby can be used to write Common Gateway Interface (CGI) scripts.
resides and runs on the server side, and the information may be passed to and from the
browser and server.
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 mainta inable.
Ruby can be used for developing Internet and intranet applications.
Ruby can be installed in Windows and POSIX environments.
Ruby can easily be connected to DB2, MySQL, Oracle, sqlite3 and Sybase.
Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts.
Ruby is available for every common computing platform.
Ruby file will have an extension .rb
Embedded Ruby
Ruby provides a program called ERB (Embedded Ruby), written by Seki Masatoshi. ERB
allows you to put Ruby codes inside an HTML file. ERB reads along, word for word, and
then at a certain point, when it encounters a Ruby code embedded in the document, it
starts executing the Ruby code. You need to know only two things to prepare an ERB
document
If you want some Ruby code executed, enclose it between <% %>.
If you want the result of the code execution to be printed out, as a part of the output,
enclose the code between <%= %>.
To run the program using the command-line utility erb. Followed by ruby file name with
extension. Type this in ruby cmd prompt
Example: erb [Link]
1. Scalars
2. Arrays
3. Hashes
Numeric literals:
1. All numeric data types in ruby are descendants of the Numeric class.
2. The immediate child classes of Numeric are float and Integer.
3. The integer class has two child classes, Fixnum and Bignum.
4. An integer literal that fits into the range of a machine word, which is often 32bits, is a
Fixnum object.
String:
1. All string literals are String objects, which are sequence of bytes that represents
characters.
2. Ruby’ string literals are related to those of Perl in that there are two categories
a. Single quoted
b. Double quoted
3. Single quoted string literal cannot include characters specified with escape sequences,
such as newline characters (\n).
4. If an actual single quote character is needed in a string literal that is delimited by single
quotes, the embedded single quote is preceded by a backslash.
Example: ‘I\’ll meet you at 5\’ near coffee day’
5. If an escape sequence is embedded in a single quoted string literal, each character in the
sequence is taken literally as itself. The sequence \n in the following string literal will be
treated as two characters that is a backslash and an n.
Example: ‘some apples are red, \n some are green’.
6. Representing strings with an alternate notation:
Sometimes we want to represent strings that are rich in met characters, such as single
quotes, double quotes and more for these situations; we have %q and %Q notations.
Examples: %q is for single quoted strings without single quote type as it is
puts %q[as i said, "this is ruby class."]
puts %q[this is not a tab: \t]
puts %Q[this is not a tab: \t]
7. If a string literal with the same characteristics as single quoted strings is needed but you
want to use a different delimiter, precede the delimiter with q.
Example: %q$Don’t you think she’s pretty?$
8. If the new delimiter is a parenthesis, a brace, a bracket, or a pointed bracket, the left
element of the pair must be used on the left, and the right element must be used on the
right.
Example: %q<Don’t you think she’s pretty?>
%q(My name is, “raghu, ‘iam from mysore’”)
%q{Another string.}
9. Double quoted string literal differ from single quoted literals in two ways:
10. First, they can include special characters specified with escape sequences; second, the
values of variable names can be interpolated into the string, which means that their values
are substituted for their names.
11. In many situations, special characters that are specified with escape sequences must be
included in string literals.
Example: “Runs \t hits \t errors”
12. A different delimiter can be specified for string literals with the characteristics of double-
quoted strings by preceding the new delimiter with Q as follows:.
13. Example: %Q@”why not learn ruby?” , he asked@
14. The null string can be denoted with either ‘ ’ or “ ”.
Local variables
Class variables
Instance variables
Global variables
Local variables
Class variable:
1. A class variable name starts with @@ sign.
2. They need to be initialized before use.
3. A class variable belongs to the whole class and can be accessible from anywhere inside
the class.
4. If the value will be changed at one instance, it will be changed at every instance.
class Student
@@no_of_Students = 0
def initialize(id, name, addr)
@std_id = id
@std_name = name
@std_addr = addr
end
def display_details()
puts "Student id #@std_id"
puts "Student name #@std_name"
puts "Student address #@std_addr"
end
def total_no_of_Students()
@@no_of_Students = @@no_of_Students+ 1
puts "Total number of Students: #@@no_of_Students"
end
end
# Create Objects
cust1 = [Link]("1", "raghu", "Mysore")
cust2 = [Link]("2", "Guru", "Mandya")
# Call Methods
cust1.total_no_of_Students ()
cust2.total_no_of_Students ()
Instance variables
1. An instance variable name starts with a @ sign.
2. It belongs to one instance of the class and can be accessed from any instance of the class
within a method.
3. They only have limited access to a particular instance of a class.
class Student
def initialize(id, name, addr)
@std_id = id
@std_name = name
@std_addr = addr
end
def display_details()
puts "Student id #@std_id"
puts "Student name #@std_name"
puts "Student address #@std_addr"
end
end
# Create Objects
cust1 = [Link]("1", "raghu", "Mysore")
cust2 = [Link]("2", "Guru", "Mandya")
# Call Methods
cust1.display_details()
cust2.display_details()
Global variables
1. A global variable name starts with a $ sign.
2. Its scope is globally, means it can be accessed from anywhere in a program.
3. An uninitialized global variable will have a nil value.
4. It is advised not to use them as they make programs cryptic and complex.
$global_variable = 10
class Class1
def print_global
puts "Number of student is #$global_variable"
end
end
class Class2
def print_global
puts "Global variable in Class2 is #$global_variable"
end
end
class1obj = [Link]
class1obj.print_global
class2obj = [Link]
class2obj.print_global
Numeric operator:
1. The precedence rules of a language specify which operator is evaluated first when two
operators that have different levels of precedence appear in an expression and are
separated only by an operand.
2. The associativity rules of a language specify which operator is evaluated first when two
operators with the same precedence level appear in an expression and are separated only
by an operand.
3. The precedence and associativity of the numeric operators are given in table below:
4. Note that Ruby does not include the increment (++) and decrement (--) operators found in
all of the C-based languages.
5. Ruby includes the Math module, which has methods for basic trigonometric and
transcendental functions. Among these methods are cos (cosine), sin (sine), log
(logarithm), sqrt (square root), and tan (tangent).
6. Ruby implementation is an interactive interpreter, which is very useful to the student of
Ruby.
7. It allows one, to type any Ruby expression and get an immediate response from the
interpreter.
8. The interactive interpreter’s name is Interactive Ruby, whose acronym, IRB, is the name
of the program that supports it.
9. For example, if the command prompt is a percent sign (%), one can type % irb
irb(main):001:0>10*2
=>20
10. The lengthy default prompt can be easily changed. We prefer the simple “>>“ prompt.
The default prompt can be changed to this with
the following command: irb(main):002:0> conf.prompt_i = “>>”
String Methods:
1. The Ruby String class has more than 75 methods. A few of which are described in this
section.
2. The String method for catenation is specified by plus (+), which can be used as a binary
operator. This method creates a new string from its operands:
Example: >> “Happy” + “ “ + “Holidays!”
=> “Happy Holidays!”
3. The << method appends a string to the right end of another string, which, of course,
makes sense only if the left operand is a variable. Like +, the << method can be used as a
binary operator. For example, in the interactions
4. The first assignment creates the specified string literal and sets the variable mystr to
reference that memory location. If mystr is assigned to another variable, that variable will
reference the same memory location as mystr:
5. Now both mystr and yourstr reference the same memory location: the place that has the
string “Wow!”. If a different string literal is assigned to mystr, Ruby will build a memory
location with the value of the new string literal and mystr will reference that location. But
youtstr will still reference the location with “Wow”.
6. If you want to change the value of the location that mystr references, but let mystr
reference the same memory location, the replace method is used.
Example: >>mystr=”Wow”!
=>”Wow!”
>>youtstr=mystr
=>”Wow!”
>>[Link](“mysore”)
=>”mysore”
>>mystr
=>”mysore”
>>yourstr
=>”mysore”
7. Among these are the ones shown in Table below; all of them create new strings.
8. Note that, after upcase is executed, the value of str is unchanged (it is still “Frank”), but
after upcase! is executed, it is changed (it is “FRANK”).
9. Ruby strings can be indexed, somewhat as if they were arrays. The indices begin at zero.
The brackets of this method specify a getter method. The catch is that the getter method
returns the ASCII code, rather than the character. To get the character, the chr method
must be called.
Example: >> str=”She”
=>”She”
>>str[1]
=> 104
>> str[1].chr
=>”h”
10. A multicharacter substring of a string can be accessed by including two numbers in the
brackets, in which case the first is the position of the first character of the substring and
the second is the number of characters in the substring.
Example: >> str=”She”
=> “She”
>> str[1,2]
=> “he”
11. Specific characters of a string can be set with the setter method, [ ]=, as in the following
interaction.
Example: >> str=”Mysore”
=> “Mysore”
>> str[3,3]=”uru”
=>”uru”
>> str
=> “Mysuru”
12. The usual way to compare strings for equality is to use the == method as an operator.
>> “snowstorm”==”snowstorm”
=>true
>>”mysore”==”mysuru”
=>false
and its parameter have the same types and the same values.
>> 7 == 7.0
=> true
>> [Link]?(7.0)
=> false
15. To facilitate ordering, Ruby includes the “spaceship” operator, <=>, which returns -1 if the second
operand is greater than the first, 0 if the two operands are equal, and 1 if the first operand is greater than
the second. “Greater in this case means that the text in question belongs later alphabetically.
>> “apple” <=> “prune”
=> -1
>> “grape” <=> “grape”
=> 0
>> “grape” <=> “apple”
=> 1
16. The repetition operator is specified with an asterisk (*). It takes a string as its left operand
and an expression that evaluates to a number as its right operand.
>> “More! “ * 3
=> “More! More! More! “
Screen Output
1. Output is directed to the screen with the puts method (or operator). We prefer to treat it as
an operator. The operand for puts is a string literal. A newline character is implicitly
appended to the string operand. If the value of a variable is to be part of a line of output,
the #{...} notation can be used to insert it into a double-quoted string literal, as in the
following interactions: The value returned by puts is nil, and that is the value returned
after the string has been displayed.
>> name = “sun”
=> “sun”
>> puts “My name is #{name}”
My name is sun
=>nil
2. The print method is used if you do not want the implied newline that puts adds to the end
of your literal string.
3. The way to convert a floating point value to a formatted string is with a variation of the C
language function sprintf. This function, which also is named sprintf, takes a string
parameter that contains a format code followed by the name of a variable to be converted
Example: str = sprintf(“%.2f”, total)
Keyboard Input:
1. Keyboard input is certainly useful for other applications. The gets method gets a line of
input from the keyboard. The retrieved line includes the newline character. If the newline
is not needed, it can be discarded with chomp:
>> name = gets
apples
=> “apples\n”
>> name = [Link]
=> “apples”
2. This code could be shortened by applying chomp directly to the value returned by gets:
>> name = [Link]
apples
=> “apples”
3. If a number is to be input from the keyboard, the string from gets must be converted to an
integer with the to_i method, as in the following interactions:
>> age = gets.to_i
27
=> 27
4. If the number is a floating-point value, the conversion method is to_f:
>> age = gets.to_f
27.5
=> 27.5
5. We must mention that there is a similar method, to_s, to which every object responds.
The method converts the value of the object to which it is sent to a string.
6. In puts method, puts implicitly converts its operand to a string, to_s is not often explicitly
called.
Example: Create with a text editor and stored in a file with an extension .rb
MVC Architecture:
Model
The Model component corresponds to all the data-related logic that the user works with. This can
represent either the data that is being transferred between the View and Controller components or
any other business logic-related data. For example, a Customer object will retrieve the customer
information from the database, manipulate it and update it data back to the database or use it to
render data.
View
The View component is used for all the UI logic of the application. For example, the Customer
view will include all the UI components such as text boxes, dropdowns, etc. that the final user
interacts with.
Controller
Controllers act as an interface between Model and View components to process all the business
logic and incoming requests, manipulate data using the Model component and interact with the
Views to render the final output. For example, the Customer controller will handle all the
interactions and inputs from the Customer View and update the database using the Customer
Model. The same controller will be used to view the Customer data.
Ruby has a complete collection of statements for controlling the execution flow through its
programs. This section introduces the control expressions and control statements of ruby.
Control expressions:
The expressions upon which statement control flow is based are Boolean expressions. They can
be either of the constants true or false, variables, relational expressions or compound
expressions. A control expression that is a simple variable is true if its value is anything except
nil.
If its value is nil, it is false.
Relational Expression:
A relational expression has two operands and a relational operator.
Relational operators can have any scalar valued expression for their operands. The relational
operator are shown in table
Selection Statements:
Control statements require some syntactic container for sequences of statements whose execution
they are meant to control. The ruby form of such containers is to use a simple sequence of
statements terminated with else or end.
Ruby’s if statement is similar to that of other languages. One syntactic difference is that there are
no parentheses around the control expression,
Example:
if a>10
b=a+2
end
1. An if construct can include elsif (note that it is not spelled elseif) clauses, which provide
a way of having a more readable sequence of nested if constructs.
Syntax:
if conditional [then]
code...
[elsif conditional [then]
code...]...
[else
code...]
end
Note: Must use "then" keyword when using 1-line syntax
Example: if x = = 3 then puts "x is 3" end
Example1:
if snowrate < 1
puts “Light snow”
elsif snowrate<2
puts “moderate snow”
else
puts “heavy snow”
end
2. Ruby has an unless statement, which is the same as it’s if statement except that the
inverse of the value of the control expression is used.
Executes code if conditional is false. If the conditional is true, code specified in the else clause is
executed. unless is the exact opposite of if. It’s a negated if.
x=1
unless x>=2
puts "x is less than 2"
else
puts "x is greater than 2"
end
3. Ruby includes two kinds of multiple selection constructs, both named case. One ruby
case construct, which is similar to a switch, has the following form.
Syntax:
case expression
when value then
--statement sequence
when value then
--statement sequence
[else
--statement sequence]
end
Example1:
capacity=gets.to_i
case capacity
when 0 then
puts "You ran out of gas."
when 1..20 then
puts "The tank is almost empty. Quickly, find a gas station!"
when 21..70 then
puts "You should be ok for now."
when 71..100 then
puts "The tank is almost full."
else
puts "Error: capacity has an invalid value (#{capacity})"
end
Example2:
print "Enter your day: "
day = [Link]
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
Example3:
case in_val
when -1 then
neg_count +=1
when 0 then
zero_count +=1
pos_count +=1
else
puts “error in_val is out of range”
end
no break statements are needed at the ends of the selectable statement sequences in this
construct.
4. The second form of case constructs uses a Boolean expression to choose a value to be
produced by the construct. The general form of this case is as follows:
Syntax:
case
When Boolean expression then expression
When Boolean expression then expression
…
When Boolean expression then expression
else expression
end
The semantics of this construct is straightforward. The Boolean expressions are evaluated, one at
a time until one evaluates to true. The value of the whole construct is the value of the expression
that corresponds to the true Boolean expression.
Loop statements:
The ruby while and for statements are similar to those of C and its decedents.
The bodies of both are sequences of statements that end with end.
The general form of the while statements are as follows:
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.
Syntax:
while control expression
loop body statement(s)
end
Example:
x=4
while x >= 1
# statements to be executed
puts "welcome to vviet"
x=x–1
# while loop ends here
end
until Loop
The until statement is similar to the while statement except that the inverse of the value of the
control expression is used. 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:
# code to be executed
end
Example:
var = 7
# using until loop
# here do is optional
until var == 11 do
# code to be executed
puts var * 10
var = var + 1
# here loop ends
end
do..while Loop
For those situations where a loop is needed in which the conditional termination is at some
position in the loop other than the top, ruby’s has an infinite loop construct and loop exit
statements. The body of the infinite loop construct is called a code block.
Code blocks can appear in two forms, one where the delimiters are braces and one where the
delimiters are the reserved words begin and end.
The structure of unconditional loop is as follows:
Loop
Code block
Syntax:
loop do
# code to be executed
break if Boolean_Expression
end
Example1:
loop do
puts "welcome to mysore"
val = '7'
# using boolean expressions
if val == '7'
break
end
# ending of ruby do..while loop
end
There are two ways to control an infinite loop, the break and next statements. These statements
can be made conditional by putting them in then clause of an if construct. The break statement
causes control to go to the first statement in the code block.
Example1:
sum=0
loop
begin
dat =gets.to_i
if dat <0 break
sum+=dat
end
end
Example2:
sum=0
loop
begin
dat=gets.to_i
if dat< 0 next
sum+=dat
end
end
In the first construct above, the loop is terminated when a negative value is input. In the second,
negative values are not added to sum, but the loop continues.
Ruby does not have a general for statement, but it includes convenient ways to construct the
counting loops implemented with for statements in other common languages.
Fundamentals of arrays:
Ruby includes two structured classes or types, arrays and hashes. Arrays in ruby are more
flexible than those of most of the other languages. An array is a collection of different or similar
items, stored at contiguous memory locations. The idea is to store multiple items of the same
type together which can be referred to by a common name.
In Ruby, numbers, strings, etc all are primitive types but arrays are of objects type i.e arrays are
the collection of ordered, integer-indexed objects which can be store number, integer, string,
hash, symbol, objects or even any other array. In general, an array is created by listing the
elements which will be separated by commas and enclosed between the square brackets[].
A Ruby array is constructed by calling: new method with zero, one or more than one arguments.
Syntax:
arrayName = [Link]
exm = [Link](10)
puts [Link]
1. 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=[Link](5,”hi”)
[“hi”, “hi”, “hi”, “hi”, “hi”]
Actually, this approach is rarely useful, because not only is each element given the same
value, but also each is given the same reference. All of them reference the same object.
So, if one is changed, all are changed.
2. Array elements are referenced through subscripts delimited by brackets([ ]), which is
actually a getter method that is allowed to be used as a unary operator. Likewise, [ ] = is a
setter method.
Example: list = [2,4,6,8]
[2,4,6,8]
Second=list[1]
4
List[3]=9
List
[2,4,6,9]
3. The length of an array is dynamic; elements can be added or removed from an array using
the methods described.
[Link]
4
The for-in statements:
The for-in statement is used to process the elements of an array. The following code computes
the sum of all of the values in list. 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
Explanation:
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.
Example1:
Sum=0
list=[2,4,6,8]
for value in list
Sum +=value
end
[2,4,6,8]
Sum
20
Example2:
i = "Sudo Placements"
# using for loop with the range
for a in 1..5 do
puts i
end
4. The scalar variable in a for-in takes on the values of the list array, one at a time. Notice
that the scalar does not get reference to array elements, it gets the values.
Example:
list=[1,3,5,7]
[1,3,5,7]
for value in list
value +=2
end
[1,3,5,7]
list
[1,3,5,7]
5. A literal array value can be used in the for-in construct, as in the following:
list=[2,4,6]
[2,4,6]
for index in [0,1,2]
puts “for index=#{index}, the value is #{list[index]}”
end
6. Built in methods for arrays and lists: Ruby introduces a few of the many built in
methods. Ruby has four methods for this purpose Unshift and shift which deal with the
left end of arrays Pop and push, which deal with the right end of array
The shift method removes and returns the first element of the array object to which it is sent.
Example: list=[3, 7,13,17]
[3,7,13,17
First=[Link]
3
list
[7,13,17]
The subscripts of all of the other elements in the array are reduced by 1 as a result of the shift
operation.
The pop method removes and returns the last element from the array object to which it is sent.
Example: list=[3, 7,13,17]
[3,7,13,17
First=[Link]
17
List
[3,7,13]
The unshift method takes a scalar or an array literal as a parameter. The scalar or array literal is
appended to the beginning of the array. This results in an increase in the subscripts of all other
array elements.
list=[2,4,6]
[2,4,6]
[Link](8,10)
[Link](0)
[2,4,6,8,10]
[0,2,4,6,8]
Either pop and unshift or push and shift can be used to implement a queue in an array, depending
on the direction the queue should grow.
7. Array concat.
While push is a convenient way to add literal elements to an array, if an array is to be catenated
to the end of another array, another method, concat, is used.
List1=[1,3,5,7]
[1,3,5,7]
List2=[2,4,6,8]
[2,4,6,8]
[Link](list2)
[1,3,5,7,2,4,6,8]
8. If two arrays need to be catenated together and the result saved as a new array, the
plus(+) method can be used as a binary operator
Example: list1=[0.1,2.4,5.6,7.9]
[0.1,2.4,5.6,7.9]
List2=[3.4,2.1,7.5]
[3.4,2.1,7.5]
List3=list1+list2
[0.1,2.4,5.6,7.9,3.4,2.1,7.5]
Note that neither list1 nor list 2 are affected by the plus method:
10. The include? Predicate method searches an array for a specific object
Example:
List =[2,4,8,16]
[2,4,8,16]
[Link]?(4)
True
[Link]?(10)
False
11. The sort method sorts the elements of an array, as long as ruby knows how to compare
those elements. The most commonly sorted elements are either numbers or strings and
ruby knows how to compare numbers with numbers and strings with strings.
Example:
List= [16,8,4,2]
[16,8,4,2]
[Link]
[2,4,8,16]
List2=[“joy”,”fred”,”mike”,”low”]
[“joy”,”fred”,”mike”,”low”]
[Link]
[“fred”,”joy”,”low”,”mike”]
12. If the sort method is sent to an array that has mixed types, ruby produces an error
message indicating the comparison failed.
Example: list =[2,”joy”,8,”fred”]
[2,”joy”,8,”fred”]
[Link]
Argument error
Sort returns a new array and does not change the array to which it is sent. The mutator method
sort! , sorts the array to which it is sent, in place.
In some situations, arrays represent sets. There are three methods that perform set operations on
two arrays. All are used as binary infix operators.
They are &, for set intersection. -, for set difference, and |, 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]
Example:
index=0
names=[Link]
while(name=gets)
names[index]=[Link]
index +=1
if [Link]>10
break
end
end
[Link]!
puts “the sorted array”
for name in names
puts name
end
Hashes
A Hash is a collection of key-value pairs like this: "employee" = > "salary". It is similar to an
Array, except that indexing is done via arbitrary keys of any object type, not an integer index.
Which is used to identify the data element. Because hash functions are used to find specific
elements in an associative array, associative arrays often are called hashes. The two fundamental
differences between arrays and hashes are as follows
First, arrays use numeric subscripts to address specific elements, whereas hashes use string
values(the keys) to address elements, second, the elements in arrays are ordered by subscript, but
the elements in hashes are not.
1. Like arrays, hashes can be created in two ways, with the new method or by assigning a
literal to a variable. In hash literal each element is specified by a key/value pair, separated
by the symbol =>. Hash literal are delimited by braces
Example: Kids_Age={“appu”=>20,”pappu”=>23, ”bose”=>22, ”bare”=>22}
=>{“appu”=>20,”pappu”=>23, ”bose”=>22, ”bare”=>22}
2. If the new method is sent to the hash class without a parameter, it creates an empty hash,
signified by { }.
>> my_hash=[Link]
=>{ }
3. An individual value element of a hash can be referenced by subscripting the hash name
with a key. The same brackets used for array element access are used to specify the
subscripting operation.
Kids_Age[“bose”]
=>22
4. 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.
>>Kids_Age[“bose”]=5
=>{“appu”=>20,”pappu”=>23, ”bose”=>5, ”bare”=>22}
5. An element is removed from a hash with the delete method, which takes an element key
as a parameter.
Kids_Age.delete(“bose”)
=>5
=>Kids_Age
=>{“appu”=>20,”pappu”=>23, ”bare”=>22}
Example 1:
>> Kids_Age ={“appu”=>20,”pappu”=>22}
=>{“appu”=>20,”pappu”=>22}
>>Kids_Age={}
Example 2:
>>salaries={“fred”=>47000,”mike”=>80000}
=>{“fred”=>47000,”mike”=>80000}
>>[Link]
=>{}
7. The has_key? Predicate method is used to determine whether an element with a specific
key is in a hash.
Example:
>>Kids_Age.has_key?(“appu”)
=>true
>>Kids_Age.has_key?(“raghu”)
=>false
8. The keys and values of s hash can be extracted into arrays with the methods keys and
values.
Example:
>>Kids_Age.keys
=>{“appu”,”pappu”}
>>Kids_Ages.values
=>{20,22}
Methods:
Method is a collection of statements that perform some specific task and return the result.
Methods allow the user to reuse the code without retyping the code. Methods are time savers and
help the user to reuse the code without retyping the code.
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.
A method definition starts with the 'def' keyword followed by the method name.
Method parameters are specified between parentheses following the method name.
The method definition ends with 'end' keyword on the bottom.
syntax:
def print_data(value)
puts value
end
Defining & Calling the method: In Ruby, the method defines with the help of def keyword
followed by method_name and end with end keyword. A method must be defined before calling
and the name of the method should be in lowercase. Methods are simply called by its name. You
can simply write the name of method whenever you call a method.
Example:
# Here Myclass is the method name
def Myclass
# statements to be displayed
puts "Welcome to Ruby portal"
Syntax:
>>end
>>a=1
>>b=2
>>swap(a,b)
=>1
>>a
=>1
>>b
=>2
A method can specify the value it returns in two ways, explicitly and implicitly.
The return statement takes an expression as its parameter. The value of the expression is returned
when the return is executed. A method can have any number of return statements, including
none.
If there are no return statements in a method or if execution arrives at the end of the method
without encountering a return, its implicitly returned objects is the value of the last expression
evaluated in the method.
Example:
def date_time1
return [Link]
end
def date_time2
[Link]
end
Classes:
A class defines the template for a category of objects, of which any number can be created.
Ruby is an ideal object-oriented programming language. ... A class is like a blueprint that allows
you to create objects and to create methods that relate to those objects. For example, you might
use a Shape class to make different shapes like Rectangle, Square, Circle, and so on. An object is
an instance of a class. object is an instance of a class. Class is a blueprint or template from
which objects are created. Object is a real world entity. Class is a group of similar objects.
Class Definition
The class may contain a class variable, instance variable, and method, as well as calls to
methods that execute in the class context at read time, such as attr_accessor.
The name of an instance variable must begin with an at sign (@), which distinguishes
instance variables from other variables.
A class can have a constructor, which in ruby is a method with the name initialize, which
is used to initialize instance variables to values.
A constructor can take any number of parameters, which are treated as local variables,
and therefore their names begin with lowercase letters or underscores.
The class declaration is terminated by the end keyword.
Example1:
class Stack2_class
def initialize(len=100)
@stack_ref=[Link](len)
@max_len=len
@top_index=-1
end
end
Example2:
class Stack2_class
def initialize(len=100)
@stack_ref=[Link](len)
@max_len=len
@top_index=-1
end
def push(number)
if @top_index==@max_len
puts “error in push-stack is full”
else
@top_index +=1
@stack_ref[@top_index]=number
end
end
def pop()
if @top_index==-1
puts “error in pop stack is empty”
else
@top_index -=1
end
end
def top()
if @top_index >-1
return @stack_ref[@top_index]
else
puts “error in top no elements”
end
end
def top2
if @top_index >0
return @stack_ref[@top_index -1]
else
puts “error in top2 there are not 2 elements”
end
end
def empty()
@top_index==-1
end
end
mystack=Stack2_class.new(50)
[Link](42)
[Link](29)
puts “top elements is #{[Link]}”
puts “second from the top is #{mystack.top2}”
[Link]
[Link]
[Link]
Classes in ruby are dynamic in the sense that members can be added at any time.
Access Control:
The 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 defined.
class My_class
def initialize(one)
@one= one
@two= one
end
# A getter for @one
def one
@one
end
# A setter for @one
def one=(my_one)
@one=my_one
end
end
var = My_class.new('Mike')
puts [Link]
output: Mike
Ruby getters and setters Method:
In a Ruby class we may want to expose the instance variables (the variables that are defined
prefixed by @ symbol) to other classes for encapsulation. Then, in that case, we use the getter
and setter methods. These methods allow us to access a class’s instance variable from outside
the class. Getter methods are used to get the value of an instance variable while the setter
methods are used to set the value of an instance variable of some class.
Example 1: Simple get method
class Myclass
# Constructor to initialize
# the class with a name
# instance variable
def initialize(name)
@web = name
end
Output :
[Link]
end
def website
@website
end
Output :welcome
to Mysore
1. attr_reader : This accessor generates the automatic Getter method for the given item.
2. attr_writer : This accessor generates the automatic Setter method for the given item.
3. attr_accessor : This accessor generates the automatic Getter & Setter method for the
given item.
# Constructor to initialize
# the class with a name
# instance variable
def initialize(website)
@website = website
end
# Constructor to initialize
# the class with a name
# instance variable
def initialize(website)
@website = website
end
def initialize(website)
@website = website
end
[Link]="to Mysore"
puts [Link]
The three levels of access control for methods are defined as follows.
1. Public
2. Private
3. Protected
Public access means the methods can be called by any code. Protected access means that only objects of
the defining class and its sub classes may call the method. Private access means 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. So, no code can ever call the private methods of
another object.
Access control for methods in Ruby is dynamic, so access violations are detected only during
execution. The default methods access is public, but it can also be protected or private. There are two
ways to specify the access control, both of which use functions with the same names as the access levels,
private, protected and public.
Syntax:
class My_class
def meth1
…
end
private
def meth7
…
end
protected
def meth11
..
end
…
end
The alternative is to call the access control functions with the names of the specific methods as
parameters.
Syntax:
class My_class
def meth1
…
end
def meth7
…
end
def meth11
..
end
…
Private:meth7,…
Protected:meth11,…
end
The times method repeatedly executes the block. This is a different approach to control of a subprogram,
of which the block is clearly a form. The most commonly used iterator is each, which is often used to go
through arrays and apply a block to each element. For this, it is convenient to allow blocks to have
parameters. Blocks can have parameters, which appear at the beginning of the block, delimited by vertical
bars ( | ).
>>list=[2,4,6,8]
=>[2,4,6,8]
>>[Link] {|value| puts value}
2
4
6
8
=>[2,4,6,8]
2. The each iterator works equally well on array literals, as in the following:
>>[“hi”, “hello”,”fine”].each {|name| puts name}
Hi
Hello
Fine
=>[“hi”, “hello”,”fine”]
If each is called on a hash, two block parameters must be included, one for the key and one for the
value:
3. The upto iterator method is used like times, except that the last value of the counter is given as a
parameter. For example
>>[Link](8) {|value| print value}
5678
=>5
4. The step iterator method takes a terminal value and a step size as parameters and generates the
values from that of the object to which it is sent and the terminal value. For example
>>[Link](6,2) {|value| puts vlaue}
0
2
4
6
=>0
5. The collect iterator method takes the elements from an array, one at a time, like each, and puts the
values generated by the given block into a new array. For example
>> list=[5,10,15,20]
=>[5,10,15,20]
>>[Link]{|value| value=value-5}
=>[0,5,10,15]
>>list
=>[5,10,15,20]
>>[Link]!{|value| value=value-5}
=>[0,5,10,15]
>>list
=>[0,5,10,15]
Pattern Matching
The Basics of Pattern Matching
In Ruby, the pattern-matching operation is specified with the matching operators =~, for positive
matches, and !~ , for negative matches. Patterns are placed between slashes ( /). For example, in the
following interactions the right operand pattern is matched against the left operand string:
The result of evaluating a pattern-matching expression is the position in the string where the pattern
matched.
The split method is frequently used in string processing. The method uses its parameter, which is a
pattern, to determine how to split the string object to which it is sent into substrings. For example, the
interactions.
puts the words from str into the words array, where the words in str are defined to be terminated with
either a space, a period, or a comma, any of which could be followed by more white-space
characters.
Substitutions
Sometimes the substring of a string that matched a pattern must be replaced by another string. Ruby’s
String class has four methods designed to do exactly that. The most basic of these, the substitute
method, sub, takes two parameters: a pattern and a string (or an expression that evaluates to a string
value). The sub method matches the pattern against the string object to which it is sent. If sub finds a
match, the matched substring is replaced by its second parameter, as in the following interactions:
The gsub method is similar to sub, except that it finds all substring matches and replaces all of them
with its second parameter:
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!. The following
interactions illustrate how gsub! works:
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:
Overview of Rails:
1. Rails are a software development framework for Web-based applications—in particular those
that access databases.
3. Rails was developed by David Heinemeier Hansson in the early 2000s and was released to
the public in July 2004.
4. Rails, like some other Web development frameworks, such as Tapestry and Struts, is based
on the Model–View–Controller (MVC) architecture for applications.
5. Figure below shows the components and actions of a request and response in a Rails
application that uses a database.
8. The controller part of a Rails application, which is implemented as one or more Ruby classes,
controls the interactions among the data model, the user, and the view.
9. The controller receives user input, interacts with the model, and provides views of data and
processing results back to the user.
10. The developer must design and build the actions that are required by the application,
implemented as methods in the controller classes.
11. The model part of a Rails application maintains the state of the application, whether that state
is internal and alive only during execution or is a permanent external database.
12. The developer must design and build a model of the application’s domain.
13. The design of the model often includes a database that stores the data of the model.
14. There are two fundamental principles that guided the development of Rails.
a. The first principle has the acronym DRY, which stands for Do not Repeat Yourself.
b. In Rails, DRY means that every element of information appears just once in the
system.
c. This minimizes the memory required by the system.
d. In addition, changes to the system are highly localized, making them both easier and
less error prone.
a. The second principle is named convention over configuration.
b. In Rails, the structure of an application is dictated by the MVC architecture.
c. The connections between the different parts are established and maintained by
convention, rather than being specified in a configuration document.
d. For example, the names of database tables and their associated controller classes are
intimately related by convention.
15. Rails use a JavaScript library named Prototype to support Ajax and interactions with the
JavaScript model of the document being displayed by the browser.
16. Rails also provide other support for developing Ajax, including producing visual effects.
Document Requests
1. Rails is a Web application development framework.
3. Before one can use Rails, the system must be downloaded and installed on one’s computer.
4. For Windows users, one simple way to do this is to download the complete software system
named Instant Rails from [Link]
5. Instant Rails, which was developed by Curt Hibbs, includes Ruby, Rails, MySQL, several
Web servers, and everything else needed to use these technologies together. Installing Instant
Rails is quick and easy.
6. Instant Rails is a self-contained system. It does not reside in the global Windows
environment, so interactions with it must be done through a special command window.
10.A click on the black I in the upper-left part of this window produces a small menu.
[Link] the Rails Applications entry in this menu opens another menu, whereupon selecting
the Open Ruby Console Window entry opens a command-line window in the rails_aps
subdirectory of the directory in which Instant Rails was installed.
[Link] in turn opens a Rails command window, which is similar in appearance to a Windows
Command Prompt window. In using Instant Rails, Rails commands cannot be given in a
normal command window—only in a Rails command window.
[Link] you are running Windows and the IIS server, you may need to stop that server before using
Rails. Also, if MySQL is running, it, too, must be stopped, because InstantRails will start its
own MySQL.
[Link], we move to the examples directory and create a new Rails application named greet with
the following command:
[Link] under the specific application directory—in this case, greet—11 subdirectories are
created, the most interesting of which at this point is app. The app directory has four
subdirectories: models, views, and controllers—which correspond directly to the MVC
architecture of a Rails application—and helpers.
[Link] following command is given in the greet directory to create the controller.
21.>ruby script/generate controller say
Before the application can be tested, a Rails Web server must be started. A server is started with the
server script from the script directory. The default server is Mongrel, but the Apache and WEBrick
servers are also available within Rails. Because it is the default Rails server, Mongrel can be started
with the following command at the application prompt:
>ruby script/server