Ruby Introduction
Ruby Introduction
"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”
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”]
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
//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
(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:
(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}