SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Downloaden Sie, um offline zu lesen
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




         #

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
farhan amjad
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
imypraz
 
AOS Lab 2: Hello, xv6!
AOS Lab 2: Hello, xv6!AOS Lab 2: Hello, xv6!
AOS Lab 2: Hello, xv6!
Zubair Nabi
 
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel" You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
Peter Hlavaty
 

Was ist angesagt? (20)

Java I/O
Java I/OJava I/O
Java I/O
 
Ruby
RubyRuby
Ruby
 
A brief introduction to SQLite PPT
A brief introduction to SQLite PPTA brief introduction to SQLite PPT
A brief introduction to SQLite PPT
 
Introduction to Vim
Introduction to VimIntroduction to Vim
Introduction to Vim
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
 
Firewall(linux)
Firewall(linux)Firewall(linux)
Firewall(linux)
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
OOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOPOOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOP
 
SHELL PROGRAMMING
SHELL PROGRAMMINGSHELL PROGRAMMING
SHELL PROGRAMMING
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
AOS Lab 2: Hello, xv6!
AOS Lab 2: Hello, xv6!AOS Lab 2: Hello, xv6!
AOS Lab 2: Hello, xv6!
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel" You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Dive into ROP - a quick introduction to Return Oriented Programming
Dive into ROP - a quick introduction to Return Oriented ProgrammingDive into ROP - a quick introduction to Return Oriented Programming
Dive into ROP - a quick introduction to Return Oriented Programming
 

Andere mochten auch

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
 

Andere mochten auch (15)

Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
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
 

Ähnlich wie 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
 

Ähnlich wie 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?
 

Mehr von Ranjith Siji

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

Mehr von 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
 

Kürzlich hochgeladen

+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@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
+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...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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, ...
 

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 #