SlideShare ist ein Scribd-Unternehmen logo
1 von 40
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…??

Weitere ähnliche Inhalte

Was ist angesagt?

C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
Scala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To KnowScala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To KnowLightbend
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating stringsJancypriya M
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useMukesh Tekwani
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does notSergey Bandysik
 
Strings in Python
Strings in PythonStrings in Python
Strings in Pythonnitamhaske
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesRasan Samarasinghe
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
Quick python reference
Quick python referenceQuick python reference
Quick python referenceJayant Parida
 

Was ist angesagt? (20)

C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
C# programming
C# programming C# programming
C# programming
 
Scala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To KnowScala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To Know
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating strings
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Core C#
Core C#Core C#
Core C#
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Swift Study #3
Swift Study #3Swift Study #3
Swift Study #3
 
Knolx session
Knolx sessionKnolx session
Knolx session
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
String in c
String in cString in c
String in c
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
 

Andere mochten auch

Sin conexion: Un web comic de Kevin Corner.
Sin conexion: Un web comic de Kevin Corner.Sin conexion: Un web comic de Kevin Corner.
Sin conexion: Un web comic de Kevin Corner.Kevin Corner
 
Interview skills slideshow
Interview skills slideshowInterview skills slideshow
Interview skills slideshowBeatriz Garcia
 
BE CoNTRARIAN
BE CoNTRARIANBE CoNTRARIAN
BE CoNTRARIANRoy Osing
 
Bfo community profile
Bfo community profile Bfo community profile
Bfo community profile sandraolgap
 
Course syllabus
Course syllabusCourse syllabus
Course syllabusGing Bhoon
 
Hidden Hills Farm Horse Boarding
Hidden Hills Farm Horse BoardingHidden Hills Farm Horse Boarding
Hidden Hills Farm Horse BoardingSamuel H Sagett
 

Andere mochten auch (8)

Unit22
Unit22Unit22
Unit22
 
Fb affiliate income wokshop
Fb affiliate income wokshopFb affiliate income wokshop
Fb affiliate income wokshop
 
Sin conexion: Un web comic de Kevin Corner.
Sin conexion: Un web comic de Kevin Corner.Sin conexion: Un web comic de Kevin Corner.
Sin conexion: Un web comic de Kevin Corner.
 
Interview skills slideshow
Interview skills slideshowInterview skills slideshow
Interview skills slideshow
 
BE CoNTRARIAN
BE CoNTRARIANBE CoNTRARIAN
BE CoNTRARIAN
 
Bfo community profile
Bfo community profile Bfo community profile
Bfo community profile
 
Course syllabus
Course syllabusCourse syllabus
Course syllabus
 
Hidden Hills Farm Horse Boarding
Hidden Hills Farm Horse BoardingHidden Hills Farm Horse Boarding
Hidden Hills Farm Horse Boarding
 

Ähnlich wie Ruby: An Introduction to the Dynamic and Object-Oriented Scripting Language

Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technologyppparthpatel123
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in ScalaAyush Mishra
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 

Ähnlich wie Ruby: An Introduction to the Dynamic and Object-Oriented Scripting Language (20)

Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 
ppt30
ppt30ppt30
ppt30
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 

Kürzlich hochgeladen

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Kürzlich hochgeladen (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

Ruby: An Introduction to the Dynamic and Object-Oriented Scripting Language

  • 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
  • 10. Basic data types  Numbers  Strings  Ranges  Arrays  Hashes  Boolean
  • 11. Numbers Numbers Integers Float Fixnum Bignum (Numbers between -2^62 & 2^62-1 or -2^30 & 2^30-1)
  • 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
  • 15. Boolean • true • false Any value evaluate to true, only nil evaluate to false.
  • 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
  • 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 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
  • 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 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
  • 35. 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
  • 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()
  • 38. 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
  • 39. Advantages  Better Access Control  Portable and extensible with third-party library  Interactive environment