SlideShare una empresa de Scribd logo
1 de 38
Descargar para leer sin conexión
Ruby Programming
What is Ruby ?
• Ruby – Object Oriented Programming
    Language
• Written 1995 by Yukihiro Matsumoto
• Influenced by Python,Pearl,LISP
• Easy to understand and workwith
• Simple and nice syntax
• Powerful programming capabilities

                                       #
Advantages
•   Powerful And Expressive
•   Rich Library Support
•   Rapid Development
•   Open Source
•   Flexible and Dynamic
Install Ruby
• On Fedora
    – Rpms are available
•   ruby-1.8.6.287-8.fc11.i586
•   ruby-devel
•   ruby-postgres
•   ruby-docs
•   ruby-racc
•   ruby-docs
                                 #
Types
• Command “ruby”
• The extension is .rb




                         #
Ruby Documents
• Command ri
• Example
  – ri class
  –




                            #
helloPerson.rb
•   # First ruby programme
•   def helloPerson(name)
•    result = "Hello, " + name
•    return result
•   end
•   puts helloPerson("Justin")


                                 #
Execute Programme
•   $ ruby helloPerson.rb
•   Hello, Justin
•   Nice and simple
•   Can use irb – interactive ruby shell
•   # is for comments like //



                                           #
Ruby variables
• def returnFoo
• bar = "Ramone, bring me my cup."
• return bar
• end
• puts returnFoo
•


                                     #
Kinds of Variables
•   Global variable - $ sign
•   instance variable - @ sign
•   Class Variable - @@ sign
•   Local Variable – no sign
•   Constants – Capital Letters



                                  #
Global Variable
• Available everywhere inside a
  programme
• Not use frequently




                                  #
instance variable
•   Unique inside an instance of a class
•   Truncated with instance
•   @apple = Apple.new
•   @apple.seeds = 15
•   @apple.color = "Green"
•


                                           #
•   class Course
                               Classes
•    def initialize(dept, number, name, professor)
•     @dept = dept
•     @number = number
•     @name = name
•     @professor = professor
•    end
•    def to_s
•     "Course Information: #@dept #@number - #@name [#@professor]"
•    end
•    def
•     self.find_all_students
•     ...
•    end
•   end
                                                                 #
Classes
• Initialize – is the constructor
• Def – end -> function
• Class-end -> class




                                    #
Define Object
•   class Student
•    def login_student
•      puts "login_student is running"
•    end
•   private
•    def delete_students
•    puts "delete_students is running"
•    end
•   protected
•    def encrypt_student_password
•     puts "encrypt_student_password is running"
•    end
•   end
                                                   #
Define Object
• @student = Student.new
• @student.delete_students # This will fail
• Because it is private
•




                                          #
Classes consist of methods
       and instance variables
•   class Coordinate
•         def initialize(x,y) #constructor
•             @x = x # set instance variables
•             @y = y
•         end
•         def to_s # string representation
•            "(#{@x},#{@y})"
•         end
•   end
•   point = Coordinate.new(1,5)
•   puts point
•   Will output (1,5)                           #
Inheritance
•         class AnnotatedCoordinate < Coordinate
•            def initialize(x,y,comment)
•                              super(x,y)
•                                    @comment = comment
•            end
•            def to_s
•                                    super + "[#@comment]"
•           end
•         End
•   a_point =
•   AnnotatedCoordinate.new(8,14,"Centre");
•   puts a_point
•   Out Put Is ->   (8,14)[Centre]


                                                             #
Inheritance
• Inherit a parent class
• Extend functions and variables
• Add more features to base class




                                    #
Polymorphism
• The behavior of an object that varies
  depending on the input.
•
•




                                          #
Polymorphism
•   class Person
•    # Generic features
•   end
•   class Teacher < Person
•    # A Teacher can enroll in a course for a semester as either
•    # a professor or a teaching assistant
•    def enroll(course, semester, role)
•     ...
•    end
•   end
•   class Student < Person
•    # A Student can enroll in a course for a semester
•    def enroll(course, semester)
•     ...
•    end
•   end                                                            #
Calling objects
• @course1 = Course.new("CPT","380","Beginning
  Ruby Programming","Lutes")
• @course2 = GradCourse.new("CPT","499d","Small
  Scale Digital Imaging","Mislan", "Spring")
• p @course1.to_s
• p @course2.to_s




                                                  #
Calling Objects
• @course1 that contains information
  about a Course
• @course2 is another instance variable,
  but it contains information about a
  GradClass object
•



                                           #
Arrays and hashes
•   fruit = ['Apple', 'Orange', 'Squash']
•   puts fruit[0]
•   fruit << 'Corn'
•   puts fruit[3]




                                            #
Arrays
• << will input a new element
• Last line outputs the new element




                                      #
Arrays More...
•   fruit = {
•     :apple => 'fruit',
•     :orange => 'fruit',
•     :squash => 'vegetable'
•   }
•   puts fruit[:apple]
•   fruit[:corn] = 'vegetable'
•   puts fruit[:corn]
                                 #
Arrays More...
• h = {"Red" => 1, "Blue" => 2, "Green" =>
  3}
• CORPORATE
• p h["Red"]
• Outpus -> 1
• h["Yellow"] = 4
• p h["Yellow"]
• Outputs -> 4
                                         #
Decision structures
•   age = 40
•   if age < 12
•     puts "You are too young to play"
•   elsif age < 30
•     puts "You can play for the normal price"
•   elsif age == 35
•     puts "You can play for free"
•   elsif age < 65
•     puts "You get a senior discount"
•   else
•     puts "You are too old to play"
•   end
                                                 #
while
• clock = 0
• while clock < 90
• puts "I kicked the ball to my team mate
  in the " + count.to_s + "
• minute of the match."
• clock += 1
• end

                                        #
Iterators
• fruit = ['Apple', 'Orange', 'Squash']
• fruit.each do |f|
• puts f
• end




                                          #
Iterators
• Keyword - do -
• Instance variable |f|
• Print f means print the instance of the
  loop




                                            #
Iterators
• fruit = ['Apple', 'Orange', 'Squash']
• fruit.each_with_index do |f,i|
• puts "#{i} is for #{f}"
• end
•



                                          #
Iterators
• Here f is the instance
• Index is i
• Will get two variables




                            #
Iterators
• fruit = ['Apple', 'Orange', 'Squash']
• for i in 0...fruit.length
• puts fruit[i]
• end
•



                                          #
Iterators
• For loop
• Same old syntax
• But 'each' loop is smart to handle an
  array
• 'each' dont need a max cutoff value.



                                          #
case...when
•   temperature = -88
•   case temperature
•     when -20...0
•             puts "cold“; start_heater
•     when 0...20
•             puts “moderate"
•     when 11...30
•             puts “hot”; drink_beer
•     else
•             puts "are you serious?"
•   end
                                          #
Exception handling
• begin
• @user = User.find(1)
• @user.name
• rescue
• STDERR.puts "A bad error occurred"
• end
•
                                       #
Thanks




         #

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Ruby
RubyRuby
Ruby
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
 
Interface in java
Interface in javaInterface in java
Interface in java
 
C# Generics
C# GenericsC# Generics
C# Generics
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Sql
SqlSql
Sql
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 
Python Dictionary.pptx
Python Dictionary.pptxPython Dictionary.pptx
Python Dictionary.pptx
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Php string function
Php string function Php string function
Php string function
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
12 SQL
12 SQL12 SQL
12 SQL
 

Destacado

Sapphire Presentation for Review_CPG_Food.PPTX
Sapphire Presentation for Review_CPG_Food.PPTXSapphire Presentation for Review_CPG_Food.PPTX
Sapphire Presentation for Review_CPG_Food.PPTX
John V. Counts Sr.
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
Manoj Kumar
 
Sapphire Presentation
Sapphire PresentationSapphire Presentation
Sapphire Presentation
usama17
 

Destacado (14)

Ruby Programming Language - Introduction
Ruby Programming Language - IntroductionRuby Programming Language - Introduction
Ruby Programming Language - Introduction
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Why Ruby
Why RubyWhy Ruby
Why Ruby
 
Lemme tell ya 'bout Ruby
Lemme tell ya 'bout RubyLemme tell ya 'bout Ruby
Lemme tell ya 'bout Ruby
 
Why I Love Ruby On Rails
Why I Love Ruby On RailsWhy I Love Ruby On Rails
Why I Love Ruby On Rails
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Sapphire Presentation for Review_CPG_Food.PPTX
Sapphire Presentation for Review_CPG_Food.PPTXSapphire Presentation for Review_CPG_Food.PPTX
Sapphire Presentation for Review_CPG_Food.PPTX
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Gemstones
GemstonesGemstones
Gemstones
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Sapphire Presentation
Sapphire PresentationSapphire Presentation
Sapphire Presentation
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
 
Gemstones
GemstonesGemstones
Gemstones
 

Similar a Introduction to Ruby

Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1
Pavel Tyk
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
Wen-Tien Chang
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang
 

Similar a Introduction to Ruby (20)

Rapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on RailsRapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on Rails
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
Continuous Integration For Rails Project
Continuous Integration For Rails ProjectContinuous Integration For Rails Project
Continuous Integration For Rails Project
 
Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1
 
Ruby
RubyRuby
Ruby
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
Javascript
JavascriptJavascript
Javascript
 
Python assignment help
Python assignment helpPython assignment help
Python assignment help
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Redis, Resque & Friends
Redis, Resque & FriendsRedis, Resque & Friends
Redis, Resque & Friends
 
并发模型介绍
并发模型介绍并发模型介绍
并发模型介绍
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented Programmers
 
Test First Teaching
Test First TeachingTest First Teaching
Test First Teaching
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting CraftsmanshipLinux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
 

Más de Ranjith Siji

Ubuntu 10.04 Installation Guide
Ubuntu 10.04 Installation GuideUbuntu 10.04 Installation Guide
Ubuntu 10.04 Installation Guide
Ranjith Siji
 

Más de Ranjith Siji (14)

Wikipedia presentation full
Wikipedia presentation fullWikipedia presentation full
Wikipedia presentation full
 
Wikisource and schools malayalam community experience
Wikisource and schools   malayalam community experienceWikisource and schools   malayalam community experience
Wikisource and schools malayalam community experience
 
Introduction to mediawiki api
Introduction to mediawiki apiIntroduction to mediawiki api
Introduction to mediawiki api
 
Conduct a Wikipedia Edit a-thon
Conduct a Wikipedia Edit a-thonConduct a Wikipedia Edit a-thon
Conduct a Wikipedia Edit a-thon
 
Black Holes and its Effects
Black Holes and its EffectsBlack Holes and its Effects
Black Holes and its Effects
 
Global warming
Global warmingGlobal warming
Global warming
 
Malayalam Computing tools and malayalam wikipedia
Malayalam Computing tools and malayalam wikipediaMalayalam Computing tools and malayalam wikipedia
Malayalam Computing tools and malayalam wikipedia
 
Introduction to Computer Hardware Assembling
Introduction to Computer Hardware AssemblingIntroduction to Computer Hardware Assembling
Introduction to Computer Hardware Assembling
 
Introduction to Internet And Web
Introduction to Internet And WebIntroduction to Internet And Web
Introduction to Internet And Web
 
Linux Alternative Softwares
Linux Alternative SoftwaresLinux Alternative Softwares
Linux Alternative Softwares
 
Ubuntu 10.04 Installation Guide
Ubuntu 10.04 Installation GuideUbuntu 10.04 Installation Guide
Ubuntu 10.04 Installation Guide
 
Introduction to Gnu/Linux
Introduction to Gnu/LinuxIntroduction to Gnu/Linux
Introduction to Gnu/Linux
 
FFMPEG TOOLS
FFMPEG TOOLSFFMPEG TOOLS
FFMPEG TOOLS
 
Linux Servers
Linux ServersLinux Servers
Linux Servers
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Introduction to Ruby

  • 2. What is Ruby ? • Ruby – Object Oriented Programming Language • Written 1995 by Yukihiro Matsumoto • Influenced by Python,Pearl,LISP • Easy to understand and workwith • Simple and nice syntax • Powerful programming capabilities #
  • 3. Advantages • Powerful And Expressive • Rich Library Support • Rapid Development • Open Source • Flexible and Dynamic
  • 4. Install Ruby • On Fedora – Rpms are available • ruby-1.8.6.287-8.fc11.i586 • ruby-devel • ruby-postgres • ruby-docs • ruby-racc • ruby-docs #
  • 5. Types • Command “ruby” • The extension is .rb #
  • 6. Ruby Documents • Command ri • Example – ri class – #
  • 7. helloPerson.rb • # First ruby programme • def helloPerson(name) • result = "Hello, " + name • return result • end • puts helloPerson("Justin") #
  • 8. Execute Programme • $ ruby helloPerson.rb • Hello, Justin • Nice and simple • Can use irb – interactive ruby shell • # is for comments like // #
  • 9. Ruby variables • def returnFoo • bar = "Ramone, bring me my cup." • return bar • end • puts returnFoo • #
  • 10. Kinds of Variables • Global variable - $ sign • instance variable - @ sign • Class Variable - @@ sign • Local Variable – no sign • Constants – Capital Letters #
  • 11. Global Variable • Available everywhere inside a programme • Not use frequently #
  • 12. instance variable • Unique inside an instance of a class • Truncated with instance • @apple = Apple.new • @apple.seeds = 15 • @apple.color = "Green" • #
  • 13. class Course Classes • def initialize(dept, number, name, professor) • @dept = dept • @number = number • @name = name • @professor = professor • end • def to_s • "Course Information: #@dept #@number - #@name [#@professor]" • end • def • self.find_all_students • ... • end • end #
  • 14. Classes • Initialize – is the constructor • Def – end -> function • Class-end -> class #
  • 15. Define Object • class Student • def login_student • puts "login_student is running" • end • private • def delete_students • puts "delete_students is running" • end • protected • def encrypt_student_password • puts "encrypt_student_password is running" • end • end #
  • 16. Define Object • @student = Student.new • @student.delete_students # This will fail • Because it is private • #
  • 17. Classes consist of methods and instance variables • class Coordinate • def initialize(x,y) #constructor • @x = x # set instance variables • @y = y • end • def to_s # string representation • "(#{@x},#{@y})" • end • end • point = Coordinate.new(1,5) • puts point • Will output (1,5) #
  • 18. Inheritance • class AnnotatedCoordinate < Coordinate • def initialize(x,y,comment) • super(x,y) • @comment = comment • end • def to_s • super + "[#@comment]" • end • End • a_point = • AnnotatedCoordinate.new(8,14,"Centre"); • puts a_point • Out Put Is -> (8,14)[Centre] #
  • 19. Inheritance • Inherit a parent class • Extend functions and variables • Add more features to base class #
  • 20. Polymorphism • The behavior of an object that varies depending on the input. • • #
  • 21. Polymorphism • class Person • # Generic features • end • class Teacher < Person • # A Teacher can enroll in a course for a semester as either • # a professor or a teaching assistant • def enroll(course, semester, role) • ... • end • end • class Student < Person • # A Student can enroll in a course for a semester • def enroll(course, semester) • ... • end • end #
  • 22. Calling objects • @course1 = Course.new("CPT","380","Beginning Ruby Programming","Lutes") • @course2 = GradCourse.new("CPT","499d","Small Scale Digital Imaging","Mislan", "Spring") • p @course1.to_s • p @course2.to_s #
  • 23. Calling Objects • @course1 that contains information about a Course • @course2 is another instance variable, but it contains information about a GradClass object • #
  • 24. Arrays and hashes • fruit = ['Apple', 'Orange', 'Squash'] • puts fruit[0] • fruit << 'Corn' • puts fruit[3] #
  • 25. Arrays • << will input a new element • Last line outputs the new element #
  • 26. Arrays More... • fruit = { • :apple => 'fruit', • :orange => 'fruit', • :squash => 'vegetable' • } • puts fruit[:apple] • fruit[:corn] = 'vegetable' • puts fruit[:corn] #
  • 27. Arrays More... • h = {"Red" => 1, "Blue" => 2, "Green" => 3} • CORPORATE • p h["Red"] • Outpus -> 1 • h["Yellow"] = 4 • p h["Yellow"] • Outputs -> 4 #
  • 28. Decision structures • age = 40 • if age < 12 • puts "You are too young to play" • elsif age < 30 • puts "You can play for the normal price" • elsif age == 35 • puts "You can play for free" • elsif age < 65 • puts "You get a senior discount" • else • puts "You are too old to play" • end #
  • 29. while • clock = 0 • while clock < 90 • puts "I kicked the ball to my team mate in the " + count.to_s + " • minute of the match." • clock += 1 • end #
  • 30. Iterators • fruit = ['Apple', 'Orange', 'Squash'] • fruit.each do |f| • puts f • end #
  • 31. Iterators • Keyword - do - • Instance variable |f| • Print f means print the instance of the loop #
  • 32. Iterators • fruit = ['Apple', 'Orange', 'Squash'] • fruit.each_with_index do |f,i| • puts "#{i} is for #{f}" • end • #
  • 33. Iterators • Here f is the instance • Index is i • Will get two variables #
  • 34. Iterators • fruit = ['Apple', 'Orange', 'Squash'] • for i in 0...fruit.length • puts fruit[i] • end • #
  • 35. Iterators • For loop • Same old syntax • But 'each' loop is smart to handle an array • 'each' dont need a max cutoff value. #
  • 36. case...when • temperature = -88 • case temperature • when -20...0 • puts "cold“; start_heater • when 0...20 • puts “moderate" • when 11...30 • puts “hot”; drink_beer • else • puts "are you serious?" • end #
  • 37. Exception handling • begin • @user = User.find(1) • @user.name • rescue • STDERR.puts "A bad error occurred" • end • #
  • 38. Thanks #