Ruby
Ruby is...
 A dynamic
 Open source
 Object oriented
 Interpreted Scripting Language
Ruby: the Language
 No multiple inheritance, but modules allow the
importing of methods.
 Has garbage collection.
 Exception handling, like Java.
 Any class or instance can be extended anytime
(even during runtime)
 Allows operator overloading.
Why Ruby…
 Ruby is simple and beautiful
 Variable declarations are unnecessary
 Easy to Learn.
 Variables are not typed
 Memory management is automatic
Where can we use Ruby….?
 System (n/w, RegExps)
 Web programming (using CGI)
 Agents, crawlers
 DB programming (using DBI)
 GUI (Tk, RubyMagick)
Running Ruby Code
 Run the interactive ruby shell – irb
 Run ruby from the command line – ruby
 Use the shebang! line on GNU/Linux
Lets get started….
puts 'Hello, world!'
p 'Hello, world!' # prints with newline
my_var = gets # get input
Variables
 No need to pre declare variables
 @ - instance variables (If you refer to an uninitialized instance variable,
Ruby returns nil.)
 @@ - class variables (Class variables must always have a value assigned to
them before they are used.Will raise NameError if it is uninitialized)
 $ - global variables
Methods
 Methods are defined with the def keyword followed by the method name and
an optional list of parameter names in parentheses.
 The Ruby code that constitutes the method body follows the parameter list,
and the end of the method is marked with the end keyword.
 Parameter names can be used as variables within the method body, and the
values of these named parameters come from the arguments to a method
invocation.
Syntax:
def functioname (parameter list)
body of the function
end
Basic data types
 Numbers
 Strings
 Ranges
 Arrays
 Hashes
 Boolean
Numbers
Numbers
Integers Float
Fixnum Bignum
(Numbers between
-2^62 & 2^62-1
or
-2^30 & 2^30-1)
Strings
s = „This is a new string „
earl = ”Earl”
s = “My name is #{earl}”
answer = 42
s = „The answer name is „ + answer.to_s
str = “Another string”
str = %q[String]
str = %Q[Another string]
str = <<EOF
Long long long
multiline text
EOF
Ranges
 Inclusive range
my_range = 1 .. 3
my_range = 'abc' .. 'abf'
 Non-inclusive range
my_range = 1 … 5
my_range = 'abc' … 'abf„
Ruby allows us to use ranges in a variety
of ways:
• Sequences (1..100)
• Conditions (result = case score
when 0..40: "Fail"
when 41..60: "Pass“ )
• Intervals (if ((1..10) === 5)
puts "5 lies in (1..10)"
end )
Hashes
 Hashes (sometimes known as
associative arrays, maps, or
dictionaries) are similar to
arrays in that they are
indexed collections of
object references.
 Can index a hash with
objects of any type: strings,
regular expressions, and so
on.
 Eg:
 my_hash = {
'desc' => {'color' =>
'blue',},
1 => [1, 2, 3]
}
 print my_hash['desc']['color']
will return
blue
Boolean
• true
• false
Any value evaluate to true, only nil
evaluate to false.
Symbols
 An identifier whose first character is a
colon ( : )
 Symbol is not
 ->string
 ->variable
 ->constant
 Eg
current_situation = :good
puts "Everything is fine" if current_situation == :good
puts "PANIC!" if current_situation == :bad
Example
 Using Strings:
person1 = { “name” => "Fred", “age” => 20, “gender” => “male” }
person2 = { “name” => "Laura", “age” => 23, “gender” => “female” }
 Using Symbols
person1 = { :name => "Fred", :age => 20, :gender => :male }
person2 = { :name => "Laura", :age => 23, :gender => :female }
Blocks
 Chunks of code between braces or
between do- end
Eg:
5.times do
puts "Blocks are powerful"
end
Blocks With parameters
def this_many_times(num)
counter = 0
while counter < num
yield
counter += 1
end
end
this_many_times(5) do
puts "Blocks are powerful"
end
Operators
 Unary (+ and -)
 Exponentiation (**)
 Arithmetic (=,-,*,/,%)
 Logical (~, &, |, ^)
 Equality (==, !=, =~, !~, ===)
 Comparison (<, <=, >, >=, <=>)
 Boolean (&&, ||, !, and, or, not)
 Conditional (?:)
 Assignment (+=,-=,*=,/=)
Control structures
Conditional Loops
*If *for
*Unless *while and until
*case
If and If…else
SYNTAX:
 if expression if expression
code code
end else
end
 The code between if and end is
executed if (and only if) the expression
evaluates to something other than
false or nil.
Eg:
if num > 0
print “num > 0”
elsif num < 0
print “num < 0”
else
print “num = 0”
end
Unless
 Executes code only if an associated
expression evaluates to false or nil.
SYNTAX:
# single-way unless statement
unless condition
code
end
# two-way unless statement
unless condition
code
else
code
end
Eg:
unless num == 0
print “num not equals
0”
else
print “num equals 0”
end
Case
 Multiway conditional
name = case name = if x == 1 then "one"
when x == 1 then "one" elsif x == 2 then "two"
when x == 2 then "two" elsif x == 3 then "three"
when x == 3 then "three" elsif x == 4 then "four"
when x == 4 then "four" else "many"
else "many" end
end
While
 Execute a chunk of code while a
certain condition is true, or until
the condition becomes true.
 The loop condition is the Boolean
expression that appears between
the while or until and do
keywords.
 While loop executes its body if the
condition evaluated is true and
 Unless loop is executed if the
condition evaluates to false or nil.
 Eg:
#Print from 10 to 0 using while
x = 10 # Initialize a loop counter variable
while x >= 0 do # Loop while x is greater than or equal to 0
puts x # Print out the value of x
x = x - 1 # Subtract 1 from x
end # The loop ends here
# Count back up to 10 using an until loop
x = 0 # Start at 0 (instead of -1)
until x > 10 do # Loop until x is greater than 10
puts x
x = x + 1
end # Loop ends here
For/in
 Executes code once for each element
in expression.
Syntax:
for variable_name in range
code block
end
Eg:
for i in 0..9
print i, “ ”
end
#=> 0 1 2 3 4 5 6 7 8 9
Class
 A class is an expanded concept of a data structure: instead of holding only
data, it can hold both data and functions.
 A template definition of the methods and variables in a particular kind of
object
 In ruby,the first letter of the class name must be in upper case
 Syntax
class class_name
class members declaration and definition
end
Objects
 A class provides the blueprints for objects, so basically an object is created
from a class. We declare objects of a class using new keyword.
 Syntax:
obj_name=classname.new
 Eg:
circle=Shape.new
INITIALIZE METHOD
 The initialize method is a standard Ruby class method and works almost same
way as constructor works in other object oriented programming languages.
 Useful when you want to initialize some class variables at the time of object
creation.
Eg:
def initialize(length,breadth)
@l=length
@b=breadth
end
Example-Classes & Objects
class BankAccount
def interest_rate
@@interest_rate = 0.2
end
def calc_interest ( balance )
puts balance * interest_rate
end
def accountNumber
@accountNumber
puts "account number is : #{@accountNumber}"
end
end
account = BankAccount.new()
account.calc_interest( 1000 )
account.accountNumber(70)
Encapsulation
 Ability for an object to have certain methods and attributes
available for use publicly (from any section of code), but for others
to be visible only within the class itself or by other objects of the
same class.
Eg
class Person
def initialize(name)
set_name(name)
end
def name
@first_name + ' ' + @last_name
end
private
def set_name(name)
first_name, last_name = name.split(/s+/)
set_first_name(first_name)
set_last_name(last_name)
end
def set_first_name(name)
@first_name = name
end
def set_last_name(name)
@last_name = name
end
end
p = Person.new("Fred Bloggs")
p.set_last_name("Smith")
puts p.name
Inheritance
 Allows us to define a class in terms of another class, which makes it easier
to create and maintain an application.
 Provides an opportunity to reuse the code functionality and fast
implementation tim
 Ruby does not support Multiple level of inheritances but Ruby supports
mixins.
Syntax:
class der_class_name < base_class_name
Example-Inheritance
class My_class
def print_foo()
print "I Love Ruby!"
end
end
class Derived_class < My_class
def initialize()
@arg = "I Love Ruby!"
end
def print_arg()
print @arg
end
end
my_object = Derived_class.new
my_object.print_foo
My_object.print_arg
Mixins
 A specialized implementation of multiple inheritance in which only the interface
portion is inherited.
Eg:
module A
def a1
end
def a2
end
end
module B
def b1
end
Mixins(Cont..)
def a2
end
end
class Sample
include A
include B
def s1
end
samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1
Polymorphism
 Allows a object to accept different requests of a client and
responds according to the current state of the runtime system, all
without bothering the user.
 Does not supports method overloading.
 Methods can be overridden
Method Overriding
class Box
def initialize(w,h)
@width, @height = w, h
end
def getArea
@width * @height
end
end
class BigBox < Box
def getArea
@area = @width * @height
puts "Big box area is : #@area"
end
end
box = BigBox.new(10, 20)
box.getArea()
Operator overloading
class Tester1
def initialize x
@x = x
end
def +(y)
@x + y
end
end
a = Tester1.new 5
puts(a + 3)
a += 7
puts a
Advantages
 Better Access Control
 Portable and extensible with third-party library
 Interactive environment
Queries…??

Ruby Basics

  • 1.
  • 2.
    Ruby is...  Adynamic  Open source  Object oriented  Interpreted Scripting Language
  • 3.
    Ruby: the Language No multiple inheritance, but modules allow the importing of methods.  Has garbage collection.  Exception handling, like Java.  Any class or instance can be extended anytime (even during runtime)  Allows operator overloading.
  • 4.
    Why Ruby…  Rubyis simple and beautiful  Variable declarations are unnecessary  Easy to Learn.  Variables are not typed  Memory management is automatic
  • 5.
    Where can weuse Ruby….?  System (n/w, RegExps)  Web programming (using CGI)  Agents, crawlers  DB programming (using DBI)  GUI (Tk, RubyMagick)
  • 6.
    Running Ruby Code Run the interactive ruby shell – irb  Run ruby from the command line – ruby  Use the shebang! line on GNU/Linux
  • 7.
    Lets get started…. puts'Hello, world!' p 'Hello, world!' # prints with newline my_var = gets # get input
  • 8.
    Variables  No needto pre declare variables  @ - instance variables (If you refer to an uninitialized instance variable, Ruby returns nil.)  @@ - class variables (Class variables must always have a value assigned to them before they are used.Will raise NameError if it is uninitialized)  $ - global variables
  • 9.
    Methods  Methods aredefined with the def keyword followed by the method name and an optional list of parameter names in parentheses.  The Ruby code that constitutes the method body follows the parameter list, and the end of the method is marked with the end keyword.  Parameter names can be used as variables within the method body, and the values of these named parameters come from the arguments to a method invocation. Syntax: def functioname (parameter list) body of the function end
  • 10.
    Basic data types Numbers  Strings  Ranges  Arrays  Hashes  Boolean
  • 11.
    Numbers Numbers Integers Float Fixnum Bignum (Numbersbetween -2^62 & 2^62-1 or -2^30 & 2^30-1)
  • 12.
    Strings s = „Thisis a new string „ earl = ”Earl” s = “My name is #{earl}” answer = 42 s = „The answer name is „ + answer.to_s str = “Another string” str = %q[String] str = %Q[Another string] str = <<EOF Long long long multiline text EOF
  • 13.
    Ranges  Inclusive range my_range= 1 .. 3 my_range = 'abc' .. 'abf'  Non-inclusive range my_range = 1 … 5 my_range = 'abc' … 'abf„ Ruby allows us to use ranges in a variety of ways: • Sequences (1..100) • Conditions (result = case score when 0..40: "Fail" when 41..60: "Pass“ ) • Intervals (if ((1..10) === 5) puts "5 lies in (1..10)" end )
  • 14.
    Hashes  Hashes (sometimesknown as associative arrays, maps, or dictionaries) are similar to arrays in that they are indexed collections of object references.  Can index a hash with objects of any type: strings, regular expressions, and so on.  Eg:  my_hash = { 'desc' => {'color' => 'blue',}, 1 => [1, 2, 3] }  print my_hash['desc']['color'] will return blue
  • 15.
    Boolean • true • false Anyvalue evaluate to true, only nil evaluate to false.
  • 16.
    Symbols  An identifierwhose first character is a colon ( : )  Symbol is not  ->string  ->variable  ->constant  Eg current_situation = :good puts "Everything is fine" if current_situation == :good puts "PANIC!" if current_situation == :bad
  • 17.
    Example  Using Strings: person1= { “name” => "Fred", “age” => 20, “gender” => “male” } person2 = { “name” => "Laura", “age” => 23, “gender” => “female” }  Using Symbols person1 = { :name => "Fred", :age => 20, :gender => :male } person2 = { :name => "Laura", :age => 23, :gender => :female }
  • 18.
    Blocks  Chunks ofcode between braces or between do- end Eg: 5.times do puts "Blocks are powerful" end Blocks With parameters def this_many_times(num) counter = 0 while counter < num yield counter += 1 end end this_many_times(5) do puts "Blocks are powerful" end
  • 19.
    Operators  Unary (+and -)  Exponentiation (**)  Arithmetic (=,-,*,/,%)  Logical (~, &, |, ^)  Equality (==, !=, =~, !~, ===)  Comparison (<, <=, >, >=, <=>)  Boolean (&&, ||, !, and, or, not)  Conditional (?:)  Assignment (+=,-=,*=,/=)
  • 20.
    Control structures Conditional Loops *If*for *Unless *while and until *case
  • 21.
    If and If…else SYNTAX: if expression if expression code code end else end  The code between if and end is executed if (and only if) the expression evaluates to something other than false or nil. Eg: if num > 0 print “num > 0” elsif num < 0 print “num < 0” else print “num = 0” end
  • 22.
    Unless  Executes codeonly if an associated expression evaluates to false or nil. SYNTAX: # single-way unless statement unless condition code end # two-way unless statement unless condition code else code end Eg: unless num == 0 print “num not equals 0” else print “num equals 0” end
  • 23.
    Case  Multiway conditional name= case name = if x == 1 then "one" when x == 1 then "one" elsif x == 2 then "two" when x == 2 then "two" elsif x == 3 then "three" when x == 3 then "three" elsif x == 4 then "four" when x == 4 then "four" else "many" else "many" end end
  • 24.
    While  Execute achunk of code while a certain condition is true, or until the condition becomes true.  The loop condition is the Boolean expression that appears between the while or until and do keywords.  While loop executes its body if the condition evaluated is true and  Unless loop is executed if the condition evaluates to false or nil.  Eg: #Print from 10 to 0 using while x = 10 # Initialize a loop counter variable while x >= 0 do # Loop while x is greater than or equal to 0 puts x # Print out the value of x x = x - 1 # Subtract 1 from x end # The loop ends here # Count back up to 10 using an until loop x = 0 # Start at 0 (instead of -1) until x > 10 do # Loop until x is greater than 10 puts x x = x + 1 end # Loop ends here
  • 25.
    For/in  Executes codeonce for each element in expression. Syntax: for variable_name in range code block end Eg: for i in 0..9 print i, “ ” end #=> 0 1 2 3 4 5 6 7 8 9
  • 26.
    Class  A classis an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.  A template definition of the methods and variables in a particular kind of object  In ruby,the first letter of the class name must be in upper case  Syntax class class_name class members declaration and definition end
  • 27.
    Objects  A classprovides the blueprints for objects, so basically an object is created from a class. We declare objects of a class using new keyword.  Syntax: obj_name=classname.new  Eg: circle=Shape.new
  • 28.
    INITIALIZE METHOD  Theinitialize method is a standard Ruby class method and works almost same way as constructor works in other object oriented programming languages.  Useful when you want to initialize some class variables at the time of object creation. Eg: def initialize(length,breadth) @l=length @b=breadth end
  • 29.
    Example-Classes & Objects classBankAccount def interest_rate @@interest_rate = 0.2 end def calc_interest ( balance ) puts balance * interest_rate end def accountNumber @accountNumber puts "account number is : #{@accountNumber}" end end account = BankAccount.new() account.calc_interest( 1000 ) account.accountNumber(70)
  • 30.
    Encapsulation  Ability foran object to have certain methods and attributes available for use publicly (from any section of code), but for others to be visible only within the class itself or by other objects of the same class.
  • 31.
    Eg class Person def initialize(name) set_name(name) end defname @first_name + ' ' + @last_name end private def set_name(name) first_name, last_name = name.split(/s+/) set_first_name(first_name) set_last_name(last_name) end def set_first_name(name) @first_name = name end def set_last_name(name) @last_name = name end end p = Person.new("Fred Bloggs") p.set_last_name("Smith") puts p.name
  • 32.
    Inheritance  Allows usto define a class in terms of another class, which makes it easier to create and maintain an application.  Provides an opportunity to reuse the code functionality and fast implementation tim  Ruby does not support Multiple level of inheritances but Ruby supports mixins. Syntax: class der_class_name < base_class_name
  • 33.
    Example-Inheritance class My_class def print_foo() print"I Love Ruby!" end end class Derived_class < My_class def initialize() @arg = "I Love Ruby!" end def print_arg() print @arg end end my_object = Derived_class.new my_object.print_foo My_object.print_arg
  • 34.
    Mixins  A specializedimplementation of multiple inheritance in which only the interface portion is inherited. Eg: module A def a1 end def a2 end end module B def b1 end
  • 35.
    Mixins(Cont..) def a2 end end class Sample includeA include B def s1 end samp=Sample.new samp.a1 samp.a2 samp.b1 samp.b2 samp.s1
  • 36.
    Polymorphism  Allows aobject to accept different requests of a client and responds according to the current state of the runtime system, all without bothering the user.  Does not supports method overloading.  Methods can be overridden
  • 37.
    Method Overriding class Box definitialize(w,h) @width, @height = w, h end def getArea @width * @height end end class BigBox < Box def getArea @area = @width * @height puts "Big box area is : #@area" end end box = BigBox.new(10, 20) box.getArea()
  • 38.
    Operator overloading class Tester1 definitialize x @x = x end def +(y) @x + y end end a = Tester1.new 5 puts(a + 3) a += 7 puts a
  • 39.
    Advantages  Better AccessControl  Portable and extensible with third-party library  Interactive environment
  • 40.