SlideShare uma empresa Scribd logo
1 de 100
Chhorn Chamnap
Yoolk Mango
4 Aug 2010
   Basic Ruby
   Methods
   Classes
   Method-Access Rules
   What’s in an Object?
   Classes in Depth
   What Happens When You Call a Method?
   Module
   Constants
   Self
   Scope
   Singleton Method
   Local variables
     start with a lowercase letter or an underscore
      Eg: x, string, __abc__, start_value, and firstName
     Ruby convention is to use underscores with multiple
      words (first_name)
     can't start with an uppercase letter
   Instance variables
     storing information for individual objects
     always start with a single at-sign(@)
     can start with an uppercase letter
   Class variables
     store information per class hierarchy
     follow the same rules as instance variables
     start with two at-signs: @@running_total
   Global variables
     recognizable by their leading dollar sign ($)
     $:, $1, and $/, $stdin and $LOAD_PATH
   predefined, reserved terms associated with
    specific programming tasks and contexts.
     def,
     class,
     if, and
     __FILE__
   Ruby interprets it as one of three things:
     A local variable
     A keyword
     A method call
   Here’s how Ruby decides:
    1. If the identifier is a keyword, it’s a keyword.
    2. If there’s an equal sign (=) to the right of the
       identifier, it’s a local variable.
    3. Otherwise, assumed to be a method call.
 When you load a file, Ruby looks for it in each of its
  load path.
 The last directory is the current directory.
 load is a method.
 Load file from relative directories
     load "../extras.rb"
     load "/home/users/dblack/book/code/loadee.rb"
   A call to load always loads the file you ask for.
     Good to examine the effect of changes immediately.
   Doesn’t reload files if already loaded.
     require "loadee"
     require "/home/users/code/loadee"
   Follow the same rules and conventions as
    local variables
     except, can end with ?, !, or =
   Methods are expressions that provide a value.
   In some contexts, you can’t tell, just by
    looking at an expression.
   Ruby sees all data structures and values as
    objects.
     x = "100".to_i(9)
   Methods can take arguments.
   Parentheses are usually optional.
     Many programmers use parentheses in most or all
      method calls, just to be safe.
   Have to supply the correct number of
    arguments.
   A method that allows any number of
    arguments.

    def multi_args(*x)
      puts "I can take zero or more arguments!"
    end

    multi_args(1,2,4)
    multi_args(1,2)
def default_args(a,b,c=1)
  puts "Values of variables: ",a,b,c
end

default_args(3,2)
   Ruby tries to assign values to as many variables
    as possible.
   The sponge parameters get the lowest priority.
   Required ones get priority, whether they
    occur at the left or at the right of the list.
   All the optional ones have to occur in the
    middle.

def broken_args(x,*y,z=1)
                                   syntax error
end
   Classes define clusters of behavior or
    functionality.
   Classes can respond to messages, just like
    objects.
   Objects can change, acquiring methods and
    behaviors that were not defined in their class.
   In Ruby, classes are objects.
   The new method is a constructor.
   Classes are named with constants.
   Ruby executed the code within the class just
    as it would execute any other code.
   It’s possible to reopen a class and make
    additions or changes.
   These methods defined inside a class.
   Used by all instances of the class.
   They don’t belong only to one object.
   Enables individual objects to remember state.
   Always start with @.
   Visible only to the object to which they
    belong.
   Initialized in one method definition is the
    same as in other method definitions.
   Define a special method called initialize.
   Ruby allows you to define methods that end
    with an equal sign (=).
def price=(amount)       ticket.price=(63.00)
  @price = amount        ticket.price = 63.00
end
   The attributes are implemented as reader
    and/or writer methods.
   Ruby supports only single inheritance.
   Classes can import modules as mixins.
   The class Object is almost at the top of the
    inheritance chart.
• Private methods can’t be called with an explicit receiver.


class Baker                        class Baker
  def bake_cake                      def bake_cake
    pour_flour                         pour_flour
    add_egg                            add_egg
  end                                end
  def pour_flour                   private
  end                                def pour_flour
  def add_egg                        end
  end                                def add_egg
  private: pour_flour,               end
   :add_egg                        end
end
   It’s OK to use an explicit receiver for private
    setter methods.
   The top-level method is stored as a private
    instance method of the Object class.
   Every object is “born” with certain innate
    abilities.
     object_id
     respond_to?
     send
     methods
     instance_variables
   Not uncommon to define a method called
    send.
     Then, use __send__ instead.
 public_send, a safe version of send method.
 send can call an object’s private methods
  public_send can’t.
   Every class is an instance of a class called
    Class.
   You can also create a class the same way you
    create most other objects.
    my_class = Class.new
    instance_of_my_class = my_class.new
   The class Class is an instance of itself.
   Object is a class, Object is an object.
   And Class is a class. And Object is a class, and
    Class is an object.
   Which came first?
     Ruby has to do some of this chicken-or-egg stuff
     in order to get the class and object system up and
     running.
   Classes are objects.
   Instances of classes are objects, too.
   A class object has its own methods, its own
    state, its own identity.
   When you call a method, Ruby does two
    things:
     It finds the method (method lookup).
     It executes the method. (find self).
   “one step to the right, then up.”
   How objects call their methods?
     From their class
     From the superclass and earlier ancestors of their
      class
     From their own store of singleton methods
   Instances of Class can call methods that are
    defined as instance methods in their class.
     Class defines an instance method called new.
     Ticket.new
   The class Class has two new methods as:
     a class method; Class.new
     an instance method; Ticket.new
   Instances of Class have access to the instance
    methods defined in Module.
    class Ticket
      attr_reader :venue, :date
      attr_accessor :price
   Modules are bundles of methods and
    constants.
   Modules don’t have instances.
   Consists of the functionality to be added to a
    class or an object.
   Modules encourage modular design.
   Modules are the more basic structure, and
    classes are just a specialization.
   Modules get mixed in to classes, using the
    include method, referred to as mix-ins.
   The instances of the class have the ability to
    call the instance methods defined in the
    module.
   A class can mix in more than one module.
   To resolve a message into a method:
     Its class
     Modules mixed into its class
     The class’s superclass
     Modules mixed into the superclass
     Likewise, up to Object (and its mix-in Kernel) and
      BasicObject
   Define a method twice inside the same class,
    the second definition takes precedence.
    class D
      def hello
        puts “hello”
      end
    end

    class D
      def hello
        puts “hello world”
      end
    end
   If the object’s method-lookup path includes
    more than two same methods, the first one is
    the “winner”.
   A class mixes in two or more modules.
     The modules are searched in reverse order of
     inclusion
class C
  include M
  include N
  include M
end


   Re-including a module doesn’t do anything.
   N is still considered the most recently
    included module.
   Use the super keyword to jump up to the
    next-highest definition, in the method-
    lookup path.
   The way super handles arguments:
     Called with no argument list – super
     Called with an empty argument list – super()
     Called with specific arguments – super(a,b,c)
   The Kernel module provides an instance method called
    method_missing.
   Nested module/class chains are used to
    create namespaces for classes, modules, and
    methods.
    module Tools
      class Hammer
      end
    End

    h = Tools::Hammer.new
   Begin with an uppercase letter.
    eg: A, String, FirstName, and STDIN
   (FirstName) or (FIRST_NAME) is usual.
   Can be referred to from inside the instance or
    class methods.
   You get a warning if you reassign to the
    constant.


   To modify a constant, use a variable instead.

     not redefining a constant,
     good for reloading program files
   Constants have a kind
    of global visibility or
    reachability.
   Bears a close
    resemblance to
    searching a filesystem.
   Like /, the :: means “start from the top level.”
   At every moment, only one object is playing
    the role of self.
   Self is the default object or current object.
   To know which object is self, you need to
    know what context you’re in.
   But what is self when you haven’t yet entered
    any definition block?
     The answer is that Ruby provides you with a start-
     up self at the top level.
    ruby -e 'puts self'

   main is a special term that the default self
    object.
   The keyword (class, module, or def) marks a
    switch to a new self.
   In a class or module definition, self is the class
    or module object.
   In a method definition, self is the object that
    called it.
   When a singleton method is executed, self is
    the object that owns the method.
   If the receiver of the message is self, you can
    omit the receiver and the dot.
   If both a method and a variable of a given
    name exist (talk), the variable takes
    precedence.
     To force Ruby to see as a method name, you’d
     have to use self.talk or talk().
   To call a setter method, have to supply
    object-dot-notation.
    self.first_name = “dara”
    first_name = “dara”
   Every instance variable belongs to self.
   Scope refers to the reach or visibility of
    variables and constants.
   Three types of variables: global, local, and
    class variables.
   Global scope is scope that covers the entire
    program.
   Global scope is enjoyed by global variables.
   Local scope is a basic layer of every Ruby
    program.
   Every time you cross into a class, module, or
    def keyword, you start a new local scope.
     The top level has its own local scope.
     Every class or module definition block has its own
      local scope.
     Every method definition has its own local scope.
   Provides a storage mechanism shared
    between a class and its instances.
   Visible only to a class and its instances.
   They’re class-hierarchy variables.
   Let’s say we’ve created our Ticket class.
     Ticket isn’t only a class.
     Ticket is also an object in its own right.



   defined directly on the class object Ticket.
   referred to as a class method of the class.
   Where do singleton methods live?
     The singleton class
   Every object has two classes:
     The class of which it’s an instance
     Its singleton class
   Singleton classes are anonymous.
   The << object notation means the anonymous,
    singleton class of object.
   The Well-Grounded Rubyist, David A. Black
   Metaprogramming Ruby, Paolo Perrotta

Mais conteúdo relacionado

Mais procurados

Understand oracle real application cluster
Understand oracle real application clusterUnderstand oracle real application cluster
Understand oracle real application clusterSatishbabu Gunukula
 
Understanding SQL Trace, TKPROF and Execution Plan for beginners
Understanding SQL Trace, TKPROF and Execution Plan for beginnersUnderstanding SQL Trace, TKPROF and Execution Plan for beginners
Understanding SQL Trace, TKPROF and Execution Plan for beginnersCarlos Sierra
 
Decentralised identifiers and knowledge graphs
Decentralised identifiers and knowledge graphs Decentralised identifiers and knowledge graphs
Decentralised identifiers and knowledge graphs vty
 
Oracle Client Failover - Under The Hood
Oracle Client Failover - Under The HoodOracle Client Failover - Under The Hood
Oracle Client Failover - Under The HoodLudovico Caldara
 
UKOUG - 25 years of hints and tips
UKOUG - 25 years of hints and tipsUKOUG - 25 years of hints and tips
UKOUG - 25 years of hints and tipsConnor McDonald
 
SPARQL queries on CIDOC-CRM data of BritishMuseum
SPARQL queries on CIDOC-CRM data of BritishMuseumSPARQL queries on CIDOC-CRM data of BritishMuseum
SPARQL queries on CIDOC-CRM data of BritishMuseumThomas Francart
 
Mysql wp cluster_evalguide
Mysql wp cluster_evalguideMysql wp cluster_evalguide
Mysql wp cluster_evalguideKaizenlogcom
 
Five_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptx
Five_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptxFive_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptx
Five_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptxMaria Colgan
 
Oracle Database Management Basic 1
Oracle Database Management Basic 1Oracle Database Management Basic 1
Oracle Database Management Basic 1Chien Chung Shen
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDBAlex Sharp
 
ODA Backup Restore Utility & ODA Rescue Live Disk
ODA Backup Restore Utility & ODA Rescue Live DiskODA Backup Restore Utility & ODA Rescue Live Disk
ODA Backup Restore Utility & ODA Rescue Live DiskRuggero Citton
 
Apache Spark Internals
Apache Spark InternalsApache Spark Internals
Apache Spark InternalsKnoldus Inc.
 
Automate the operation of your Oracle Cloud infrastructure v2.0
Automate the operation of your Oracle Cloud infrastructure v2.0Automate the operation of your Oracle Cloud infrastructure v2.0
Automate the operation of your Oracle Cloud infrastructure v2.0Nelson Calero
 
Oracle Flex ASM - What’s New and Best Practices by Jim Williams
Oracle Flex ASM - What’s New and Best Practices by Jim WilliamsOracle Flex ASM - What’s New and Best Practices by Jim Williams
Oracle Flex ASM - What’s New and Best Practices by Jim WilliamsMarkus Michalewicz
 
Oracle Database Management - Backup/Recovery
Oracle Database Management - Backup/RecoveryOracle Database Management - Backup/Recovery
Oracle Database Management - Backup/RecoveryChien Chung Shen
 
Oracle Open World Presentation - Oracle RMAN Best Practices for Cloud Backups
Oracle Open World Presentation - Oracle RMAN Best Practices for Cloud Backups Oracle Open World Presentation - Oracle RMAN Best Practices for Cloud Backups
Oracle Open World Presentation - Oracle RMAN Best Practices for Cloud Backups Niklas Iveslatt
 
Oracle Extended Clusters for Oracle RAC
Oracle Extended Clusters for Oracle RACOracle Extended Clusters for Oracle RAC
Oracle Extended Clusters for Oracle RACMarkus Michalewicz
 

Mais procurados (20)

Understand oracle real application cluster
Understand oracle real application clusterUnderstand oracle real application cluster
Understand oracle real application cluster
 
Understanding SQL Trace, TKPROF and Execution Plan for beginners
Understanding SQL Trace, TKPROF and Execution Plan for beginnersUnderstanding SQL Trace, TKPROF and Execution Plan for beginners
Understanding SQL Trace, TKPROF and Execution Plan for beginners
 
Decentralised identifiers and knowledge graphs
Decentralised identifiers and knowledge graphs Decentralised identifiers and knowledge graphs
Decentralised identifiers and knowledge graphs
 
Apache Spark Notes
Apache Spark NotesApache Spark Notes
Apache Spark Notes
 
Oracle Client Failover - Under The Hood
Oracle Client Failover - Under The HoodOracle Client Failover - Under The Hood
Oracle Client Failover - Under The Hood
 
UKOUG - 25 years of hints and tips
UKOUG - 25 years of hints and tipsUKOUG - 25 years of hints and tips
UKOUG - 25 years of hints and tips
 
SPARQL queries on CIDOC-CRM data of BritishMuseum
SPARQL queries on CIDOC-CRM data of BritishMuseumSPARQL queries on CIDOC-CRM data of BritishMuseum
SPARQL queries on CIDOC-CRM data of BritishMuseum
 
Mysql wp cluster_evalguide
Mysql wp cluster_evalguideMysql wp cluster_evalguide
Mysql wp cluster_evalguide
 
Five_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptx
Five_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptxFive_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptx
Five_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptx
 
Oracle Database Management Basic 1
Oracle Database Management Basic 1Oracle Database Management Basic 1
Oracle Database Management Basic 1
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
 
ODA Backup Restore Utility & ODA Rescue Live Disk
ODA Backup Restore Utility & ODA Rescue Live DiskODA Backup Restore Utility & ODA Rescue Live Disk
ODA Backup Restore Utility & ODA Rescue Live Disk
 
Apache Spark Internals
Apache Spark InternalsApache Spark Internals
Apache Spark Internals
 
Data Guard Architecture & Setup
Data Guard Architecture & SetupData Guard Architecture & Setup
Data Guard Architecture & Setup
 
Automate the operation of your Oracle Cloud infrastructure v2.0
Automate the operation of your Oracle Cloud infrastructure v2.0Automate the operation of your Oracle Cloud infrastructure v2.0
Automate the operation of your Oracle Cloud infrastructure v2.0
 
Oracle Flex ASM - What’s New and Best Practices by Jim Williams
Oracle Flex ASM - What’s New and Best Practices by Jim WilliamsOracle Flex ASM - What’s New and Best Practices by Jim Williams
Oracle Flex ASM - What’s New and Best Practices by Jim Williams
 
Oracle Database Management - Backup/Recovery
Oracle Database Management - Backup/RecoveryOracle Database Management - Backup/Recovery
Oracle Database Management - Backup/Recovery
 
Oracle Open World Presentation - Oracle RMAN Best Practices for Cloud Backups
Oracle Open World Presentation - Oracle RMAN Best Practices for Cloud Backups Oracle Open World Presentation - Oracle RMAN Best Practices for Cloud Backups
Oracle Open World Presentation - Oracle RMAN Best Practices for Cloud Backups
 
Oracle Extended Clusters for Oracle RAC
Oracle Extended Clusters for Oracle RACOracle Extended Clusters for Oracle RAC
Oracle Extended Clusters for Oracle RAC
 
Oracle Data Guard
Oracle Data GuardOracle Data Guard
Oracle Data Guard
 

Destaque

Advanced Ruby Idioms So Clean You Can Eat Off Of Them
Advanced Ruby Idioms So Clean You Can Eat Off Of ThemAdvanced Ruby Idioms So Clean You Can Eat Off Of Them
Advanced Ruby Idioms So Clean You Can Eat Off Of ThemBrian Guthrie
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaRafael Magana
 
«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»Olga Lavrentieva
 
Magic in ruby
Magic in rubyMagic in ruby
Magic in rubyDavid Lin
 
Ruby OOP: Objects over Classes
Ruby OOP: Objects over ClassesRuby OOP: Objects over Classes
Ruby OOP: Objects over ClassesAman King
 
Ruby's Object Model: Metaprogramming and other Magic
Ruby's Object Model: Metaprogramming and other MagicRuby's Object Model: Metaprogramming and other Magic
Ruby's Object Model: Metaprogramming and other MagicBurke Libbey
 
DevNexus 2017 - Building and Deploying 12 Factor Apps in Scala, Java, Ruby, a...
DevNexus 2017 - Building and Deploying 12 Factor Apps in Scala, Java, Ruby, a...DevNexus 2017 - Building and Deploying 12 Factor Apps in Scala, Java, Ruby, a...
DevNexus 2017 - Building and Deploying 12 Factor Apps in Scala, Java, Ruby, a...Neil Shannon
 
MongoDB - Ruby document store that doesn't rhyme with ouch
MongoDB - Ruby document store that doesn't rhyme with ouchMongoDB - Ruby document store that doesn't rhyme with ouch
MongoDB - Ruby document store that doesn't rhyme with ouchWynn Netherland
 
Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.
Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.
Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.IT-Доминанта
 
Object-Oriented BDD w/ Cucumber by Matt van Horn
Object-Oriented BDD w/ Cucumber by Matt van HornObject-Oriented BDD w/ Cucumber by Matt van Horn
Object-Oriented BDD w/ Cucumber by Matt van HornSolano Labs
 
HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2Sharon Wasden
 
The Black Magic of Ruby Metaprogramming
The Black Magic of Ruby MetaprogrammingThe Black Magic of Ruby Metaprogramming
The Black Magic of Ruby Metaprogrammingitnig
 
Elasticsearch Basics
Elasticsearch BasicsElasticsearch Basics
Elasticsearch BasicsShifa Khan
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java ProgrammersMike Bowler
 

Destaque (20)

Advanced Ruby Idioms So Clean You Can Eat Off Of Them
Advanced Ruby Idioms So Clean You Can Eat Off Of ThemAdvanced Ruby Idioms So Clean You Can Eat Off Of Them
Advanced Ruby Idioms So Clean You Can Eat Off Of Them
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael Magana
 
«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»
 
Beginner's Sinatra
Beginner's SinatraBeginner's Sinatra
Beginner's Sinatra
 
ZODB Tips and Tricks
ZODB Tips and TricksZODB Tips and Tricks
ZODB Tips and Tricks
 
Magic in ruby
Magic in rubyMagic in ruby
Magic in ruby
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
 
Ruby OOP: Objects over Classes
Ruby OOP: Objects over ClassesRuby OOP: Objects over Classes
Ruby OOP: Objects over Classes
 
Ruby's Object Model: Metaprogramming and other Magic
Ruby's Object Model: Metaprogramming and other MagicRuby's Object Model: Metaprogramming and other Magic
Ruby's Object Model: Metaprogramming and other Magic
 
v8 engine
v8 enginev8 engine
v8 engine
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
DevNexus 2017 - Building and Deploying 12 Factor Apps in Scala, Java, Ruby, a...
DevNexus 2017 - Building and Deploying 12 Factor Apps in Scala, Java, Ruby, a...DevNexus 2017 - Building and Deploying 12 Factor Apps in Scala, Java, Ruby, a...
DevNexus 2017 - Building and Deploying 12 Factor Apps in Scala, Java, Ruby, a...
 
MongoDB - Ruby document store that doesn't rhyme with ouch
MongoDB - Ruby document store that doesn't rhyme with ouchMongoDB - Ruby document store that doesn't rhyme with ouch
MongoDB - Ruby document store that doesn't rhyme with ouch
 
Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.
Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.
Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.
 
Object-Oriented BDD w/ Cucumber by Matt van Horn
Object-Oriented BDD w/ Cucumber by Matt van HornObject-Oriented BDD w/ Cucumber by Matt van Horn
Object-Oriented BDD w/ Cucumber by Matt van Horn
 
HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2
 
The Black Magic of Ruby Metaprogramming
The Black Magic of Ruby MetaprogrammingThe Black Magic of Ruby Metaprogramming
The Black Magic of Ruby Metaprogramming
 
Elasticsearch Basics
Elasticsearch BasicsElasticsearch Basics
Elasticsearch Basics
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 

Semelhante a Ruby object model (20)

Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for ruby
 
Java defining classes
Java defining classes Java defining classes
Java defining classes
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
Java
JavaJava
Java
 
Hemajava
HemajavaHemajava
Hemajava
 
Only oop
Only oopOnly oop
Only oop
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java session2
Java session2Java session2
Java session2
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Python_Unit_3.pdf
Python_Unit_3.pdfPython_Unit_3.pdf
Python_Unit_3.pdf
 
Java basics
Java basicsJava basics
Java basics
 
ACM init() Day 6
ACM init() Day 6ACM init() Day 6
ACM init() Day 6
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
 
Oops
OopsOops
Oops
 
C# interview
C# interviewC# interview
C# interview
 

Mais de Chamnap Chhorn

High performance website
High performance websiteHigh performance website
High performance websiteChamnap Chhorn
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web ArchitectureChamnap Chhorn
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in RefactoringChamnap Chhorn
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayChamnap Chhorn
 

Mais de Chamnap Chhorn (7)

Introduction to rails
Introduction to railsIntroduction to rails
Introduction to rails
 
High performance website
High performance websiteHigh performance website
High performance website
 
Rest and Rails
Rest and RailsRest and Rails
Rest and Rails
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in Refactoring
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
Rest in Rails
Rest in RailsRest in Rails
Rest in Rails
 

Último

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Último (20)

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

Ruby object model

  • 2. Basic Ruby  Methods  Classes  Method-Access Rules  What’s in an Object?  Classes in Depth  What Happens When You Call a Method?  Module  Constants  Self  Scope  Singleton Method
  • 3.
  • 4. Local variables  start with a lowercase letter or an underscore Eg: x, string, __abc__, start_value, and firstName  Ruby convention is to use underscores with multiple words (first_name)  can't start with an uppercase letter  Instance variables  storing information for individual objects  always start with a single at-sign(@)  can start with an uppercase letter
  • 5. Class variables  store information per class hierarchy  follow the same rules as instance variables  start with two at-signs: @@running_total  Global variables  recognizable by their leading dollar sign ($)  $:, $1, and $/, $stdin and $LOAD_PATH
  • 6. predefined, reserved terms associated with specific programming tasks and contexts.  def,  class,  if, and  __FILE__
  • 7. Ruby interprets it as one of three things:  A local variable  A keyword  A method call  Here’s how Ruby decides: 1. If the identifier is a keyword, it’s a keyword. 2. If there’s an equal sign (=) to the right of the identifier, it’s a local variable. 3. Otherwise, assumed to be a method call.
  • 8.
  • 9.  When you load a file, Ruby looks for it in each of its load path.  The last directory is the current directory.  load is a method.  Load file from relative directories  load "../extras.rb"  load "/home/users/dblack/book/code/loadee.rb"  A call to load always loads the file you ask for.  Good to examine the effect of changes immediately.
  • 10. Doesn’t reload files if already loaded.  require "loadee"  require "/home/users/code/loadee"
  • 11.
  • 12. Follow the same rules and conventions as local variables  except, can end with ?, !, or =  Methods are expressions that provide a value.  In some contexts, you can’t tell, just by looking at an expression.
  • 13. Ruby sees all data structures and values as objects.  x = "100".to_i(9)  Methods can take arguments.  Parentheses are usually optional.  Many programmers use parentheses in most or all method calls, just to be safe.
  • 14. Have to supply the correct number of arguments.
  • 15. A method that allows any number of arguments. def multi_args(*x) puts "I can take zero or more arguments!" end multi_args(1,2,4) multi_args(1,2)
  • 16. def default_args(a,b,c=1) puts "Values of variables: ",a,b,c end default_args(3,2)
  • 17. Ruby tries to assign values to as many variables as possible.  The sponge parameters get the lowest priority.
  • 18.
  • 19. Required ones get priority, whether they occur at the left or at the right of the list.  All the optional ones have to occur in the middle. def broken_args(x,*y,z=1) syntax error end
  • 20.
  • 21.
  • 22. Classes define clusters of behavior or functionality.  Classes can respond to messages, just like objects.  Objects can change, acquiring methods and behaviors that were not defined in their class.
  • 23. In Ruby, classes are objects.  The new method is a constructor.  Classes are named with constants.
  • 24. Ruby executed the code within the class just as it would execute any other code.
  • 25. It’s possible to reopen a class and make additions or changes.
  • 26. These methods defined inside a class.  Used by all instances of the class.  They don’t belong only to one object.
  • 27. Enables individual objects to remember state.  Always start with @.  Visible only to the object to which they belong.  Initialized in one method definition is the same as in other method definitions.
  • 28.
  • 29. Define a special method called initialize.
  • 30. Ruby allows you to define methods that end with an equal sign (=). def price=(amount) ticket.price=(63.00) @price = amount ticket.price = 63.00 end
  • 31. The attributes are implemented as reader and/or writer methods.
  • 32.
  • 33. Ruby supports only single inheritance.  Classes can import modules as mixins.  The class Object is almost at the top of the inheritance chart.
  • 34.
  • 35. • Private methods can’t be called with an explicit receiver. class Baker class Baker def bake_cake def bake_cake pour_flour pour_flour add_egg add_egg end end def pour_flour private end def pour_flour def add_egg end end def add_egg private: pour_flour, end :add_egg end end
  • 36. It’s OK to use an explicit receiver for private setter methods.
  • 37.
  • 38. The top-level method is stored as a private instance method of the Object class.
  • 39.
  • 40. Every object is “born” with certain innate abilities.  object_id  respond_to?  send  methods  instance_variables
  • 41.
  • 42. Not uncommon to define a method called send.  Then, use __send__ instead.  public_send, a safe version of send method.  send can call an object’s private methods public_send can’t.
  • 43.
  • 44. Every class is an instance of a class called Class.  You can also create a class the same way you create most other objects. my_class = Class.new instance_of_my_class = my_class.new
  • 45.
  • 46.
  • 47. The class Class is an instance of itself.  Object is a class, Object is an object.  And Class is a class. And Object is a class, and Class is an object.  Which came first?  Ruby has to do some of this chicken-or-egg stuff in order to get the class and object system up and running.
  • 48. Classes are objects.  Instances of classes are objects, too.  A class object has its own methods, its own state, its own identity.
  • 49.
  • 50. When you call a method, Ruby does two things:  It finds the method (method lookup).  It executes the method. (find self).
  • 51. “one step to the right, then up.”
  • 52. How objects call their methods?  From their class  From the superclass and earlier ancestors of their class  From their own store of singleton methods  Instances of Class can call methods that are defined as instance methods in their class.  Class defines an instance method called new. Ticket.new
  • 53. The class Class has two new methods as:  a class method; Class.new  an instance method; Ticket.new  Instances of Class have access to the instance methods defined in Module. class Ticket attr_reader :venue, :date attr_accessor :price
  • 54.
  • 55. Modules are bundles of methods and constants.  Modules don’t have instances.  Consists of the functionality to be added to a class or an object.  Modules encourage modular design.  Modules are the more basic structure, and classes are just a specialization.
  • 56. Modules get mixed in to classes, using the include method, referred to as mix-ins.  The instances of the class have the ability to call the instance methods defined in the module.  A class can mix in more than one module.
  • 57.
  • 58. To resolve a message into a method:  Its class  Modules mixed into its class  The class’s superclass  Modules mixed into the superclass  Likewise, up to Object (and its mix-in Kernel) and BasicObject
  • 59. Define a method twice inside the same class, the second definition takes precedence. class D def hello puts “hello” end end class D def hello puts “hello world” end end
  • 60. If the object’s method-lookup path includes more than two same methods, the first one is the “winner”.
  • 61. A class mixes in two or more modules.  The modules are searched in reverse order of inclusion
  • 62. class C include M include N include M end  Re-including a module doesn’t do anything.  N is still considered the most recently included module.
  • 63. Use the super keyword to jump up to the next-highest definition, in the method- lookup path.
  • 64. The way super handles arguments:  Called with no argument list – super  Called with an empty argument list – super()  Called with specific arguments – super(a,b,c)
  • 65. The Kernel module provides an instance method called method_missing.
  • 66. Nested module/class chains are used to create namespaces for classes, modules, and methods. module Tools class Hammer end End h = Tools::Hammer.new
  • 67.
  • 68. Begin with an uppercase letter. eg: A, String, FirstName, and STDIN  (FirstName) or (FIRST_NAME) is usual.  Can be referred to from inside the instance or class methods.
  • 69. You get a warning if you reassign to the constant.  To modify a constant, use a variable instead.  not redefining a constant,  good for reloading program files
  • 70. Constants have a kind of global visibility or reachability.  Bears a close resemblance to searching a filesystem.
  • 71. Like /, the :: means “start from the top level.”
  • 72.
  • 73. At every moment, only one object is playing the role of self.  Self is the default object or current object.  To know which object is self, you need to know what context you’re in.
  • 74.
  • 75.
  • 76. But what is self when you haven’t yet entered any definition block?  The answer is that Ruby provides you with a start- up self at the top level. ruby -e 'puts self'  main is a special term that the default self object.  The keyword (class, module, or def) marks a switch to a new self.
  • 77. In a class or module definition, self is the class or module object.
  • 78. In a method definition, self is the object that called it.
  • 79. When a singleton method is executed, self is the object that owns the method.
  • 80. If the receiver of the message is self, you can omit the receiver and the dot.
  • 81. If both a method and a variable of a given name exist (talk), the variable takes precedence.  To force Ruby to see as a method name, you’d have to use self.talk or talk().  To call a setter method, have to supply object-dot-notation. self.first_name = “dara” first_name = “dara”
  • 82. Every instance variable belongs to self.
  • 83.
  • 84.
  • 85. Scope refers to the reach or visibility of variables and constants.  Three types of variables: global, local, and class variables.
  • 86. Global scope is scope that covers the entire program.  Global scope is enjoyed by global variables.
  • 87. Local scope is a basic layer of every Ruby program.  Every time you cross into a class, module, or def keyword, you start a new local scope.  The top level has its own local scope.  Every class or module definition block has its own local scope.  Every method definition has its own local scope.
  • 88.
  • 89.
  • 90. Provides a storage mechanism shared between a class and its instances.  Visible only to a class and its instances.
  • 91.
  • 92. They’re class-hierarchy variables.
  • 93.
  • 94.
  • 95. Let’s say we’ve created our Ticket class.  Ticket isn’t only a class.  Ticket is also an object in its own right.  defined directly on the class object Ticket.  referred to as a class method of the class.
  • 96. Where do singleton methods live?  The singleton class  Every object has two classes:  The class of which it’s an instance  Its singleton class
  • 97. Singleton classes are anonymous.  The << object notation means the anonymous, singleton class of object.
  • 98.
  • 99.
  • 100. The Well-Grounded Rubyist, David A. Black  Metaprogramming Ruby, Paolo Perrotta