2. Ruby is...
A dynamic
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…
Ruby is simple and beautiful
Variable declarations are unnecessary
Easy to Learn.
Variables are not typed
Memory management is automatic
5. Where can we use 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 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
9. 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
12. 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
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 (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
16. 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
18. 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
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 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
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 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
25. 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
26. 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
27. 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
28. 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
29. 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)
30. 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.
31. 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
32. 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
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 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
36. 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
37. 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()