0% found this document useful (0 votes)
13 views

Ruby Introduction

Ruby was designed by Yukihiro Matsumoto in 1996 and runs on various platforms like Windows, Mac OS, and UNIX. It is a pure object-oriented programming language similar to Python and PER. Ruby features include being a server-side scripting language, ability to embed HTML, and syntax similar to languages like C++ and Perl. It can easily connect to databases and has a rich set of built-in functions. Ruby has scalar, array, and hash data types, with scalars including numeric and string types. Variables are assigned using assignment statements and Ruby includes some predefined implicit variables.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Ruby Introduction

Ruby was designed by Yukihiro Matsumoto in 1996 and runs on various platforms like Windows, Mac OS, and UNIX. It is a pure object-oriented programming language similar to Python and PER. Ruby features include being a server-side scripting language, ability to embed HTML, and syntax similar to languages like C++ and Perl. It can easily connect to databases and has a rich set of built-in functions. Ruby has scalar, array, and hash data types, with scalars including numeric and string types. Variables are assigned using assignment statements and Ruby includes some predefined implicit variables.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Introduction to Ruby

• Ruby was designed in Japan by Yukihiro


Matsumoto (a.k.a. Matz) and was released in
1996.
• It runs on a variety of platforms, such as
Windows, Mac OS, and the various versions of
UNIX.
• Ruby is a pure object-oriented programming
language.
Features of Ruby
• Ruby is a server-side scripting language similar to
Python and PER
• Ruby can be embedded into Hypertext Markup
Language (HTML).
• Ruby has similar syntax to that of many
programming languages such as C++ and Perl.
• Ruby can easily be connected to DB2, MySQL,
Oracle, and Sybase.
• Ruby has a rich set of built-in functions, which can
be used directly into Ruby scripts.
Scalar Types and Their Operations
• Ruby has three categories of data types:
scalars, arrays, and hashes.
• There are two categories of scalar types:
numerics and character strings
• All numeric data types in Ruby are
descendants of the Numeric class. The
immediate child classes of Numeric are Float
and Integer. The Integer class has two child
classes: Fixnum and Bignum.
Strings
• All string literals are String objects, which are
sequences of bytes that represent characters. There
are two categories of string literals: single quoted and
double quoted.
• Single-quoted string literals cannot include characters
specified with escape sequences, such as newline
characters specified with \n.
• If an actual single-quote character is needed in a string
literal, the embedded single quote is preceded by a
backslash, as in the following example:
• ‘I\’ll meet you at O\’Malleys’
• ‘Some apples are red, \n some are green’
Strings
• Double-quoted string literals differ from single-quoted
string literals in two ways: 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.
• “Runs \t Hits \t Errors”
• A double quote can be embedded in a double-quoted
string literal by preceding it with a backslash.
• “Runs \“ Hits \“ Errors”
Variables and Assignment Statements
• Naming conventions in Ruby help identify different
categories of variables. For now, we will deal with
local variables only. Other naming conventions will be
explained as needed.
• The form of variable names is a lowercase letter or an
underscore, followed by any number of uppercase or
lowercase letters, digits, or underscores.
• The letters in a variable name are case sensitive,
meaning that fRIZZY, frizzy, frIzZy, and friZZy are all
distinct names.
• However, by convention, programmer-defined
variable names do not include uppercase letters.
Display value of variable
• Double-quoted string literals can include the values
of variables.
• This is specified 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,
• “Tuesday’s high temperature was #{tue_high}”
• “Tuesday’s high temperature was 83”
• “The cost of our apple order is $#{price *quantity}”
Variables are references
• Ruby is a pure object-oriented programming
language, all of its variables are references to
objects.
• In Ruby, every data value is an object, so it
needs references only.
• Because references are typeless, there is no
point in declaring them. In fact, there is no
way to declare a variable in Ruby.
Implicit Variables
• Ruby includes some predefined, or implicit,
variables. The name of an implicit scalar
variable begins with a dollar sign.
• The rest of the name is often just one more
special character, such as an underscore (_), a
circumflex (^), or a backslash (\). This chapter
and the next include some uses of these
implicit variables.
Numeric Operators
• Most of Ruby’s numeric operators are similar
to those in other common programming
languages, so they should be familiar to most
readers.
• There are the binary operators: + for addition,
- for subtraction, * for multiplication, / for
division, ** for exponentiation, and % for
modulus.
• 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.
• 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.
• 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).
• The methods of the Math module are referenced by
prefixing their names with Math.,
• Math.sin(x).
• All of these take any numeric type as a parameter and
return a Float value.
String Methods
• The Ruby String class has more than 75
methods, a few of which are described in this
section.
• Many of these methods can be used as if they
were operators.
• Catenation is specified by plus (+)
• >> “Happy” + “ “ + “Holidays!”
• => “Happy Holidays!”
Concatenating Strings

• Ruby concatenating string implies creating one string


from multiple strings. You can join more than one
string to form a single string by concatenating them.
• Using plus sign in between strings.
string = "This is Ruby Tutorial" + “Welcome."
puts string

• Using << sign in between strings.


string = "This is Ruby Tutorial" << “Welcome."
puts string
• The << method appends a string to the right
end of another string
str=“ Today”
str<<“is Tuesday”
str=>”Today is Tuesday
• the replace method
str.replace(“Wow!”)
Common string functions
• capitalize
• Chop
• Chomp
• Upcase
• Downcase
• etc
chop vs. chomp
• Chop will remove any trailing newline or carriage
return characters "\r\n".
• Chomp leaves the string unchanged if it doesn't
end in a record separator.
• So using Chomp is safer than Chop.

"Ruby\r\n".chop =>"Ruby“
"Ruby".chop => "Rub“
"Ruby\r\n".chomp => "Ruby"
"Ruby".chomp => "Ruby"
Simple Input and Output
Example: puts “My name is #{name}”
The print method is used if you do not want the
implied newline that puts adds to the end of
your literal string.
Example: print “Hello”

A variation of the C language function sprintf.


Example: sprintf(“%5.2f”, total)
Keyboard Input
• 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.chomp
• apples
• => “apples”
• gets reads a string, gets must be converted to an
integer with the to_i method
• >> age = gets.to_i
• 27
• => 27

• >> age = gets.to_f


• 27.5
• => 27.5
Ruby – program examples
1. Hello World program
puts "Hello, Ruby!";

2. puts “enter value a”


a=gets.to_i
puts “enter value b”
b=gets.to_i
result=a+b
puts “result is : #{result}”
Selection and Loop Statements
if statement
if a > 10
b=a*2
end
if else

if snowrate < 1
puts “Light snow”
elsif snowrate < 2
puts “Moderate snow”
else
puts “Heavy snow”
end
Example
(checking marks)
a = gets.chomp.to_i
if a <50
puts "Student is fail"
elsif a >= 50 && a <= 60
puts "Student gets D grade"
elsif a >= 70 && a <= 80
puts "Student gets B grade"
elsif a >= 80 && a <= 90
puts "Student gets A grade"
elsif a >= 90 && a <= 100
puts "Student gets A+ grade"
end
unless
unless sum > 1000
puts “We are not finished yet!”
end
case statement
print "Enter your day: "
day = gets.chomp
case day
when "Tuesday"
puts 'Wear Red or Orange'
when "Wednesday"
puts 'Wear Green'
Loop statements
• Ruby has while and for statements
• The bodies of both are sequences of statements
that end with end.
• The general form of the while statement is as
follows:
while control expressions
loop body statement(s)
end
The control expression could be followed by the do
reserved word
Example (while)
x = gets.chomp.to_i
while x >= 0
puts x
x -=1
end
Ruby Until Loop
• The Ruby until loop runs until the given condition
evaluates to true
Syntax:
until conditional
code
end
Example:
i=1
until i == 10
print i*10, "\n"
i += 1
end
Infinite Loop
• There are two ways to control an infinite loop:
with the break and next statements.
• The break statement causes control to go to
the first statement following the loop body.
• The next statement causes control to go to
the first statement in the loop body.
Example:
sum=0
loop do
d=gets.to_i
if d<0 break
sum+=d
end

sum=0
loop do
d=gets.to_i
if d<0 next
sum+=d
end
• Ruby has for and for-in constructs
• Are discussed with arrays
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 common languages
• Differences between Ruby arrays and those of
other common languages such as C, C++, and Java.
• Ruby array is dynamic: It can grow or shrink
anytime during program execution.
• Ruby array can store different types of data.
Ruby arrays can be creation
1. Array.new
new is a function in class Array
e.g: list1=Array.new(5) //nil values
2. List literal assigning to a variable
e.g: list2=[2, 4, 6, 8, 5.7, ”Fred”]
Arrays
• An array created with the new method can
also be initialized by including a second
parameter,
• list1 = Array.new(5, “Ho”)
• => [“Ho”, “Ho”, “Ho”, “Ho”, “Ho”]

but every element is given the same value


Arrays
• Array elements are referenced through subscripts delimited by
brackets [ ]
• You can pass one or more than one arguments or even a range of
arguments.
Example
list=[2, 4, 6, 8]
a=list[1] # a contains value 4
b=list[2] #b contains value 4
c=list[1,3] #c contains value 4, 6, 8

• The length of an array can be retrieved with the length method, as


below:
len = list.length # value of len is 4
4
for-in statement
for variable [, variable ...] in expression [do]
code
end
Example
x = ["Blue", "Red", "Green", "Yellow", "White"]
for i in x do
puts i
end
Built-In Methods for Arrays and Lists
• unshift and shift, which deal with the left end of
arrays
⇒ The shift method removes and returns the first
element
list=[2, 4, 6, 8]
a=list.shift #a is now 2
⇒ The unshift method takes a scalar or an array
literal as a parameter and appends it to the
beginning of the array
list=[2, 4, 6, 8]
list.unshift( 1, 5)
Built-In Methods for Arrays and Lists
• pop and push, which deal with the right end
of arrays
=>The push method takes a scalar or an array
literal and adds it to the high end of the array:
list=[2, 4, 6, 8]
list.push(10, 12)
=> The pop method removes and returns the
last element
More functions
• Concat array
list1.concat(list2)
list3=list1+list2
• reverse
list.reverse
• Include?
list=[2, 4, 6, 8]
list.include?(4)
• Sort (mutator method sort!)
new_list=list.sort
list.sort! (changes in place)
Hash
• 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. They are also called associative
arrays, dictionaries or maps.
• If a hash is accessed with a key that does not
exist, the method will return nil.
• Syntax:
name = {"key1" => "value1", "key2" => "value2",
"key3" => "value3"...}
OR
name = {key1: 'value1', key2: 'value2', key3: 'va
lue3'...}
new
• If the new method is sent to the Hash class
without a parameter, it creates an empty
hash, denoted by {}:
• my_hash = Hash.new
• Ruby hash is created by writing key-value pair within
{} curly braces.
• To fetch a hash value, write the required key within []
square bracket.

Example
color = {
"Rose" => "red",
"Lily" => "purple",
"Marigold" => "yellow",
"Jasmine" => "white"
}
puts color['Rose']
puts color['Lily']
puts color['Marigold']
puts color['Jasmine']
Clear the hash
• A hash can be set to empty in one of two
ways:
• an empty hash literal can be assigned to the
hash
hi_temps={“mon”=>74, “tue”=> 78}
hi_temps={ }
• the clear method
hi_temps.clear
has_key?
• The has_key? predicate method is used to
determine whether an element with a specific
key is in a hash
example
hi_temps.has_key?(“wed”)
=>false
keys and values
• The keys and values of a hash can be
extracted into arrays with the methods keys
and values, respectively:
Example
kids_ages={“John”=>10, “Jake”=> 21, “Darcia”
=> 13}
kids_ages.keys
kids_ages.values
Methods
• A method definition includes the method’s header and a
sequence of statements, ending with the end reserved
word, that describes its actions.
• A method header is the reserved word def, the method’s
name, and optionally a parenthesized list of formal
parameters.
• Method names must begin with lowercase letters.
• If the method has no parameters, the parentheses are
omitted.
• In fact, the parentheses are optional in all cases,
• But it is common practice to include them when there are
parameters
• And omit them when there are no parameters.
• The types of the parameters are not specified in
the parameter list,
• Because Ruby variables do not have types—they
are all references to objects.
• The type of the return object is also not specified
in a method definition.
Syntax:
def methodName
code...
end
Function return
• A method can specify the value it returns in two
ways: explicitly and implicitly.
Example
def date_time1
return Time.now
end

def date_time
Time.now
end
Local Variables

• Local variables either are formal parameters or


are variables created in a method. A variable is
created in a method by assigning an object to it.
• The scope of a local variable is from the header of
the method to the end of the method.
• The name of a local variable must 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.
Parameters
• The parameter values that appear in a call to a method are
called actual parameters.
• The parameter names used in the method, which
correspond to the actual parameters, are called formal
parameters.
• In effect, scalar actual parameters specify the values of
objects, not their addresses.
• So, in Ruby, the transmission of scalar parameters is strictly
one way into the method.
• The values of the scalar actual parameters are available to
the method through its formal parameters.
• Whatever a method does to its formal parameters, it has no
effect on the actual parameters in the calling program unit.
• Example
def swap(x, y)
t=x
x=y
y=t
end

//function call
a=1
b=2
Swap(a, b)
Classes
• Classes in Ruby are like those of other
object-oriented programming languages
• A class defines the template for a category of
objects,
• An object has a state, which is maintained in
its collection of instance variables, and a
behavior, which is defined by its methods. An
object can also have constants and a
constructor.
Syntax
• The methods and variables of a class are
defined in the syntactic container that has the
following form:
class class_name
...
end
**Class names, like constant names, must
begin with uppercase letters.
• Instance variables are used to store the state
of an object. They are defined in the class
definition, and every object of the class gets
its own copy of the instance variables.
• The name of an instance variable must begin
with an at sign (@), which distinguishes
instance variables from other variables.
• A class can have a single constructor, which in Ruby is a
method with the name initialize, which is used to initialize
instance variables to values
Example

class Sum
def initialize
@a=5
@b=5
end
def sum_method
puts @a+@b
end
end
s=Sum.new
s.sum_method
Inheritance

• Subclasses are defined in Ruby with the left


angle bracket (<):
• class My_Subclass < Base_class
Blocks and Iterators
• A block is a sequence of code, delimited by
either braces or the do and end reserved
words.
• In this section, a few of the built-in iterator
methods that are designed to use blocks are
discussed.
The times iterator method
• It 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.
>> 4.times {puts “Hey!”}
Hey!
Hey!
Hey!
Hey!
(p8.rb)
Iterator each
• It is often 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:
list=[2,4,6,8]
list.each {|value| puts value}

(p9.rb)
# example on hashes
kids_ages={“John”=>10, “Jake”=> 21, “Darcia”
=> 13}
kids_ages.each {|n, a| puts “name is #{n} and
age is #{a} “ }

(r1.rb)
The upto iterator
• This method is used like times, except that the
last value of the counter is given as a
parameter:

5.upto (8) {|value| puts value}

(r2.rb)
The step iterator method
• It 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:
0.step(10, 2) {|value| puts value}

(r3.rb)
The collect iterator
• This method takes the elements from an array, one at
a time, and puts the values generated by the given
block into a new array:
• Must be assigned to new array
list=[1,2,3,4,5]
list.collect{|value| puts value}

• the mutator version of collect is probably more often


useful than the nonmutator version, which does not
save its result.
(r4.rb)
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:
str=“morning”
str=~/ing/ (returns 4 which is position of match)
Split method
• 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,
str=“Jake used to be a small child, but now it is
not.”
words=str.split(/[ .,]\s*/)(words is an array)
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 (or an
expression that evaluates to a string value).
Example:
str=“The old car is great, but old“
str.sub(/old/, “new”)
o/p: str=“The new car is great, but old“
• The gsub method is similar to sub, except that it
finds all substring matches and replaces all of
them with its second parameter:
str=“The old car is great, but old“
str.gsub(/old/, “new”)
o/p: str=“The new car is great, but new“

• However, sub and gsub have mutator versions,


named sub! and gsub!.

You might also like