You are on page 1of 99

Introduction to

Ruby

BY DEEPA ACHARYA
14.1 Origins and Uses of Ruby

 Ruby is a scripting language Developed in JApan


by Yukihiro Matsumoto about 1996
 Purely interpreted
 Somewhat easier learning because of simple
structure
 One can just write the simple logic and request for
its interpretation.
 Notable characteristics
 Regular expressions based on Perl
 Dynamic objects based on JavaScript
14.2 Scalar Types and Their
Operations

 Three categories of data


 Scalars
 Arrays
 Hashes
 All values are objects, including numeric values
,arrays etc
14.2 Numeric Literals
 Numeric data are descendants of class Numeric. It has 2 child classes
 Float and Integer

Integer has 2 child classes


 Fixnum - Fits to 32 bits
 Bignum - integer literal that is outside the Fixnum range
 Fixnum-bignum coersion is possible(visa versa)

 Underscore characters can appear embedded in integer literals. Ruby


ignores such underscores, allowing large numbers to be slightly more
readable. For example, instead of 124761325, 124_761_325 can be used.

 Float literals may not have a decimal point first or last. The decimal point
must be both preceded and followed by at least one digit. So, .435 is not
a legal literal in Ruby.
14.2 String Literals
 Single or double quoted
 Double quoted has escape characters and expression
interpolation
 Single quoted have not escape characters or expression
interpolation
 q$...$ for a single quoted string
 $ can be other characters
 q<Don’t you think flower’s pretty?>
 <{([ as the start delimiter must be matched by >})] at the end
 Q$...$ for a double quoted string
 Q@”Why not learn Ruby?”, he asked.@
 The null string (the string with no characters) can be denoted
with either ‘‘ or ““.
14.2 Variables and Assignment
Statements
 Variables are not formally declared and do not have a fixed
type
 An identifier begins with a lower case letter or underscore
followed by letters(uc or lc) and/or digits and/or underscore
 Variables are all references to objects
 An unassigned variable has value nil
 Named constants are named like variables but have names
that begin with a capital letter
 There are some implicit variables such as $_,$^,$\ etc
 The letters in a variable name are case sensitive, meaning
that fRIZZY, frizzy, frIzZy, and friZZy are all distinct names.
 The results of executing any Ruby code can be included by
placing the code in braces and preceding the left brace with a
pound sign (#).
 For example, if the value of tue_high is 83, then the string
“Tuesday’s high temperature was #{tue_high}”
 has the following value:
“Tuesday’s high temperature was 83”
 Similarly, if the value of price is 1.65 and that of quantity is 6, then
the value of the string
 “The cost of our apple order is $#{price * quantity}”
is
 “The cost of our apple order is $9.90”
14.2 Numeric Operators

 Standard operators: + - * / %
 Integer/Integer is integer
 ** for exponentiation
 Missing: ++ and –
 Math module: cos, sin, log, sqrt, …
 The interactive Ruby interpreter IRB takes
experssions and responds with the values
Interactive Ruby
 Simply type irb at the command prompt in the directory that
contains the Ruby interpreter. For example, if the command
prompt is a percent sign (%), one can type
 % irb
 after which irb will respond with its own prompt, which is
 irb(main):001:0>

 At this prompt, any Ruby expression or statement can be typed,


that returns the value after an implication symbol (=>), as in the
following example:
 irb(main):001:0> 17 * 3
 => 51
 irb(main):002:0>
 To change the prompt to simple “>>“, type the following
command:
 irb(main):002:0> conf.prompt_i = “>>“
14.2 String Methods
 Catenation is indicated by +
 >> “Happy” + “ “ + “Holidays!”
 => “Happy Holidays!”

 << appends its right operand to the left


 Similar to an assignment operator
 += is a synonym

 >>mystr="Good "
 => "Good "
 >>mystr<<"Morning"
 => "Good Morning"
 If mystr is assigned to another  If a different string is
variable, that variable will assigned to mystr, Ruby
reference the same memory will build a memory
location as mystr:
location with the value of
the new string literal and
mystr will reference that
location. But yourstr will still
reference the location
with “Wow!”:
 Replace method makes references to refer the same memory
location
>>st1="Good"
=> "Good"
>>st2=st1
=> "Good"
>>st1.replace("Bad")
=> "Bad"
>>st1
=> "Bad"
>>st2
 "Bad“

 The append operation can also be done with the += assignment


operator. So, instead of mystr
 << “Morning”, mystr += “Morning” could be used.
String methods
 bang (!)or mutator methods modify their objects in place.
 The brackets [ ]returns the ASCII code (as a Fixnum object),
rather than the character. To get the character, the chr
method must be called, as in the following interactions:

 If a negative subscript is used as an index, the position is


counted from the right.
 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.
 Specific characters of a string can be set with the setter
method, []=, as in the following interactions:

 To compare strings for equality == operator is used.


 equal? : used to test equality, determines whether its
parameter references the same object as the one to
which it is sent. True if the receiver and argument have
the same object id.

 produces false because, although the contents of the


two string literals are the same, they are different
objects.

 eql? method, which returns true if its receiver object and


its parameter have the same types and the same
values.
 True if the receiver and argument have both the same
type and equal values.
 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.
 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.
 The left operand is replicated the number of times equal to
the value of the right operand:
14.3 Screen Output
 Operator puts displays a string on standard output
A new line is added to the output
 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:
 >> name = “Fudgy”
 => “Fudgy”
 >> puts “My name is #{name}”
 My name is Fudgy
 => nil
 The value returned by puts is nil, and that is
 Operator print displays a string without the new line
 sprintf, takes a string parameter that contains a format code
followed by the name of a variable to be converted.
 The string version is returned by the function. The format codes
most commonly used are f and d.
 str = sprintf(“%5.2f”, total)
14.3 Keyboard Input

 Function gets gets a line of input from the console (keyboard)


 gets.chomp returns the next lline of input with out the terminating new
line
 >> name = gets
 apples
 => “apples\n”
 >> name = name.chomp
 => “apples”

 This could be shortened by :


 >> name = gets.chomp
 Apples
 => “apples”
 gets.to_i returns the next line of input
converted to an integer
 >> age = gets.to_i
 27.5
 => 27
 gets.to_f returns the next line of input
converted to a float
 >> age = gets.to_f
 27
 => 27.0
 Example quadeval.rb illustrates console input and
output
 Run with the command
ruby quadeval.rb
 A program stored in a file can be run by the command
 >ruby filename
 So, our example program can be run (interpreted) with
 >ruby quadeval.rb
 the –c flag – for syntax errors
 the -w flag, to produce warning messages
 To check the syntax of our example program, the following
statement could be used:
 >ruby -cw quadeval.rb
 If the program is found to be syntactically correct, the
response to this command is as follows:
 Syntax OK
14.4 Control Expressions

 A Boolean expression
 Any value but nil is considered true
 Comparison operators
 Usual: == != < > <= >=
 Compare for order: <=>
 Compare for type and value: eql?
 Compare for equality of object: equal?
 Operator precedence and associativity
Operator Precedences
14.4 Selection and Loop Statements

 If statement
if control-expression
statements
elsif control-expression
statements
else
statements
end
 elsif can be repeated any number of times
(including 0)
14.4 Unless

 Reverses if, no else or elsif


unless control-expression
statements
end
14.4 Case Syntax

case expression
when value then
- statement sequence
when value then
- statement sequence
[else
- statement sequence]
end
 No break statements are needed at the ends of the
sequences of selectable statements in this construct:
 There are implied branches at the end of each
when clause that cause execution to exit the
construct.
14.4 Case Expression

 Syntax
case
when Boolean expression then expression
...
when Boolean expression then expression
else expression
end
 The first true Boolean expression causes the matching
expression to be evaluated as the value of the case
 The else expression is used if none of the Booleans are true
 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 xpression that corresponds to
the true Boolean expression.
 If none of the Boolean expressions is true,
the else expression is evaluated and its
value is the value of the construct.
14.4 Loops
 While loop repeats while control expression is true
 Until loop repeats until control expression is true
 loop introduces an infinite loop
A code block is a sequence of statements
delimited by braces or by keywords begin and
end
 The loop keyword is followed by a code block
 Exit from the loop is by the break statement
 The next statement causes control to go back to
the beginning of the code block
14.5 Fundamentals of Arrays

 Ruby arrays are dynamic in size and can store different types of data in
different elements
 Creating an array
 Array.new(size)

 Array.new(size, value)

 A literal list such as [2, 4, 6]

 Element access through subscript [sub]


 Element assignment through [sub]=
The length of an array is dynamic; elements can be
added to or removed from an array The length of an
array can be retrieved with the length method, as
illustrated in the following interactions:
>> len = list.length
=> 4
14.5 The for-in Statement
 Syntax
for variable in list
statements
end
 The variable takes on each value in the list
14.5 Build-In Methods for Arrays
and
 push Lists
inserts at the end of a list
 pop removes from the end of a list and returns the value
 unshift inserts at the beginning of a list
 shift removes from the front of a list and returns the value
 Arrays catenated with +
 Method reverse returns a reversed copy
 Method reverse! reverses the array
 include? searches an array
 sort sorts an array, returns a new array
 Shift

 push
 concat
 Reverse

 reverse!
 The include? predicate method searches an
array for a specific object:
 The sort method sorts the elements of an array.
 Ruby can compare numbers with numbers and strings
with strings. So, sort works well on arrays of elements of
either of these two types:

 If the sort method is sent to an array that has mixed


types, Ruby produces an error message indicating that
the comparison failed
 In some situations, arrays represent sets. There are
three methods that perform set operations on two
arrays:
 &, for set intersection;
 -, for set difference; and
 |, for set union.
14.6 Hashes
 Hashes are like arrays but use string indexes
 Indexes are keys and elements are values
 Hash elements are not ordered
 Creating a Hash
 Hash.new
 Literal hash as in {“a”=>1, “b”=>2}

 Element access using string ‘subscripts’


 Elements are added by using assignment
 Elements are removed using delete method
 The clear method removes all elements
 has_key? checks if a string is a key in a hash
 Methods keys and values return arrays of the respective
components
 The order of the hash returned by Ruby is not the same as the
order in the hash literal used to create the hash. This is
because the actual order of the hash in memory is
unpredicatable

 Subscripting

 Assigning new element


 Deleting an element from hash

 Emptying hash
 Hask_key? Method

 Keys & Values Methods


14.7 Methods

 Methods can be defined outside classes


 When a method is called without an object
reference, the default is self
14.7 Fundamentals of Methods

 Method syntax
def name [( formal-parameters )]
statements
end
 Parentheses can be omitted if there are no formal
parameters
 Return statement ends execution of the method
 With a value, it returns the value as the value of the
method
 If no return ends a method, the last expression is the
value of the method
14.7 Local Variables

 Variables used in a method are local to the


method
 Global variables with the same name are hidden
 Local variable names must begin with a
lowercase letter or an underscore
 The lifetime of a local variable from its creation to
the end of the execution of the method
14.7 Parameters
 Parameters are passed by value unless arrays and hashes
 Arrays and hashes are passed by reference
 The number of actual parameters must match the number of
formal parameters
 If
the last formal parameter is preceded by an
asterisk, it receives all actual parameters not
matched to earlier formal parameters
 Formal parameters can be assigned default values, so the
corresponding actual parameter may be omitted
 If a hash literal is the last actual parameter, the
curly braces are not required
 In this case symbols are conventionally
used as the keys

A symbol is an unquoted string


preceded by a colon
 Symbols are useful because a given
symbol name refers to the same object
throughout a Ruby program
14.8 Basics of Classes
 Syntax
class class-name

end
 Class names begin with an uppercase letter
 Instance variables have instances for each object
 Names begin with @
 Constructor is named initialize
 Members can by dynamically added and removed from a
class
 Method remove_method removes a method
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 that access cannot be
changed.
 If external access to an instance variable is
required,
access methods must be defined.
 The equals sign (=) attached to
the name of the setter method
means that the method is
assignable.
 So, all setter methods have
equals signs attached to their
names.
 The body of the one method
illustrates the Ruby design
whereby methods return the
value of the last expression
evaluated when there is no
return statement.
 In this case, the value of @one
is returned
 When an instance variable that has a getter
or setter is referenced outside the class, the at sign (@) part of the name
is not included.
 The following code that uses My_class is illustrative:
mc = My_class.new
puts “The value of one is #{mc.one}

 Because getter and setter methods are frequently needed, Ruby


provides shortcuts for both.
 If one wants a class to have getter methods for two instance variables,
@one and @two, those getters can be specified with the single
statement in the class as follows:
attr_reader :one, :two

Note that attr_reader is actually a method call, using the symbols :one
and :two as the actual parameters.

The function that similarly creates setters is called attr_writer. This function
has the same parameter profile as attr_reader.
attr_writer :one, :two

 The three levels of access control for methods are defined as
follows:
 “Public access” means that 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 access” means that the method cannot be called
with an explicit receiver object.
 Because the default receiver object is self, a private method
can be called only in the context of the current object.
 So, no code can ever call the private methods of
another object.
 The default method 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.
 One way is to call the appropriate function without
parameters.
 The alternative is to call the access control functions
with the names of the specific methods as
parameters.
 For example, the following is semantically
equivalent to the previous class definition:
Inheritance
 Subclasses are defined in Ruby with the left angle bracket (<):
class My_Subclass < Base_class
One distinctive feature of Ruby’s method access controls is that they can
be changed in a subclass simply by calling the access control functions.

 Access to a module in a class is specified with an include statement, such


as the following:
include Math
The effect of including a module is that the class gains a pointer to the
module and effectively inherits the functions defined in the module.

 In fact, when a module is included in a class, the module becomes a


proxy superclass of the class. Such a module is called a mixin, because its
functions get mixed into the methods defined in the class.

 Mixins provide a way to include the functionality of a module in any class


that needs it
14.9 Code Blocks and Iterators

 A code block is a sequence of statements delimited by


braces or by do/end
 A code block can have parameters, listed at the beginning of
the block, surrounded by vertical bars: |a, b|
 A code block may be passed to a method call, following the
actual parameters of the call
 The times iterator method provides a way to build simple
counting loops. Typically, times is
 sent to a number object, which repeats the attached block
that number of times. Consider the
 following example:
 >> 4.times {puts “Hey!”}
 Hey!
 Hey!
 Hey!
 Hey!
 => 4
 each, is used to go through arrays and apply a block to each
element.
 For this purpose, it is convenient to allow blocks to have
parameters, which, if present,appear at the beginning of the
block, delimited by vertical bars (|).
 The following example, which uses a block parameter,
illustrates the use of each:
 The upto iterator method is used like times, except
that the last value of the counter is given as a
parameter:
14.10 Pattern Matching

 Pattern matching in Ruby is based on pattern


matching in Perl
 Patterns are delimited by slashes
 =~ is the pattern matching operator
 The split method is used to split a string with
separators given by a regular expression
14.10 Remembering Matches

 Parts of a regular expression pattern can be


enclosed in parentheses
 If there is a match, the variables $1, $2 … hold the
strings matched by the parenthesized parts
 If there is a match, $`, $& and $’ hold the part of
the target before the match, the part matched
and the part after the match
14.10 Substitutions

 Method sub substitutes its second parameter for


the first match found of the first parameter
 Method gsub is similar but substitutes for all
matches
 Both methods create new strings
 sub! and gsub! change the target string
 The i modifier on a pattern causes the match to
ignore letter case
 Sub function

 Gsub! mutator
 i modifier
Introduction to
Rails
15.1 Overview of Rails
 Rails is Ruby based
 “A development framework for Web-based applications”
 Rails uses the Model-View-Controller architecture
 Model classes are responsible for maintaining data.
 View classes present the data to the user
 Controller classes perform computations and deal with user
interaction
 Rails uses an Object-Relational Mapping approach to working
with databases
 A cars table corresponds to a car class
 The rows of the table correspond to instances of the class
 The correspondence is built automatically by the Rails framework
 Rails uses a combination of Ruby code and template files to
create responses
15.1 Developer Tasks

 Design and build the model, including a


database for storing model data
 Design and implement actions
 Design and implement the views
15.2 Document requests

 The Rails framework provides much of the


superstructure necessary for a web application
 Scripts with the Rails framework set up the basic
structure
 The first Rails example serves a single static
document
15.3 Project Setup

 The InstantRails package provides all the


components needed to develop and test Rails
projects on a Microsoft Windows platform
 Start the InstantRails console
InstantRails
 Set up a rails application
rails rails1
 Generate a controller
ruby script/generate controller say
 Run the default server
ruby script/server
 The server runs for a particular application
15.3 Project Directory Structure
15.2 Request Processing
15.2 Dynamic Documents

 The next example displays the greeting but also


displays the current time
 Uses Time.now from the Ruby library
 <% … %> embeds Ruby code in template files
 <%= … %> causes the value of the executed code
to be inserted in place
 Instance variables of the controller class can be
accessed in the template file
<p> The number of seconds in a day is: <%= 60
* 60 * 24 %>
</p>
produces
<p> The number of seconds in a day is: 86400
</p>

You might also like