SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Ruby
The (good) compulsive obsession for the objects
(or the object of obsession)


An introduction to the Ruby Object Model


                          raf.magana@gmail.com
                                                  1
What you will find in this presentation
 OOP concepts
 Definition of object
 Ruby Objects
 Ruby Classes
 Objects and classes interaction
 Ruby Modules
 Ruby and Meta-programming
 Ruby Variables
 Ruby Methods
 The Top Level
                                         2
OOP concepts
Inheritance
  It allows a class to have the same behavior as another class
  Ruby uses < (less than) for inheritance: class Human < Mammal
    The default parent class is Object
Encapsulation
  To modify an object's state, one of the object's behaviors must be used
  In “my_object.something”, “something” must be a method, not a variable
Polymorphism
  It allows two or more objects respond to the same message
    person.wake_up / computer.wake_up / animal.wake_up
                                                                            3
Object? what is that?
 The OOP definition: Object = state + behavior
   state is described by variables (attributes)
   behavior is described by methods
 Every object of the same type will have its own state
 All the objects of the same type will share the same behavior




                                                                 4
Ruby Objects
A Ruby object consist of the following
  A reference to the object immediate class (interpreter stores this in ‘klass’)
  A hash table of instance variables
    Objects does not have a table of methods, they are in the class.
    Only classes can have methods.
  A set of flags: Singleton, Mark, Finalize, Taint, Exivar, Freeze, etc.




                                                                                   5
Ruby Classes (get ready to become insane)
 A Ruby class: it’s an instance object of class Class, an consists of the following:
   A reference to the object immediate class (interpreter stores this in ‘klass’)
   A hash table of instance variables
   A hash table of methods
   A set of flags: Singleton, Mark, Finalize, Taint, Exivar, Freeze, etc.
   A reference to the superclass (interpreter stores it in “super”)
      my_object.class denotes "instance of" (my_object = MyClass.new)
      MyClass.superclass denotes "inherits from" ( MyClass < OtherClass)

 In Ruby, always remember this, CLASSES ARE OBJECTS!!!

                                                                                       6
Ruby Classes
 since classes are objects, class objects are instances of other class
 “but, if classes are objects, and you just said objects doesn’t have
 methods, only classes does, so what’s going on here?”, you’d say.
   well, I have to say that a class isn’t really an object (x_X)
   look at the following code taken from the Ruby source




but a class is still an object:
* you can store instance variables
* inherits from the Object class

                                                                         7
Ruby Classes
In Ruby there are two types of classes
  “Real” classes and “meta”-classes (singleton, virtual, Eigen or ghost classes)

What is the difference?
  “meta”-classes are “Real” classes with a flag set to ‘virtual’
  a “meta”-class is created as needed and inserted in the inheritance chain before
  the object "real" class and they are hidden.
What are meta-classes useful for?
  If the instance methods of my_object are in MyClass and MyClass is an instance
  of class Class, so it can’t have its own instance methods, then where are the
  instance methods of MyClass object?
  The instance methods of MyClass object are in a meta-class, a Singleton class.


                                                                                     8
How classes and instances interact
Every method call nominate a receiver and a message.
“my_obj.my_method”: my_obj is the receiver and my_method is the message.

my_guitar = receiver; dup/play = message         Guitar = receiver; strings = message




                                                                                        9
Ruby modules
A Ruby module is an object that acts as a placeholder for classes,
methods and constants.
A module is like a class with 3 key differences
  It isn’t a class, (but it is an object and it has instance methods),
  Module is actually the superclass of Class - class Class < Module

  It cannot be instantiated (you cannot do x = MyModule.new)
  It can be mixed in a class to enhance its possibilities
A module can be two things
  A namespace, a way to regroup similar things.
  A Mixin (mixed in), they eliminate the need of multiple inheritance

                                                                         10
Ruby Modules
As a namespace   As a Mixin
                              Kernel#require

                                loads an external file

                              Module#include

                                Module#append_features

                                it makes a reference from
                                the class to the included
                                module




                                                            11
Hierarchy diagram
Kernel is a module, not a class
Object class mixes in the Kernel module
  it defines the instance methods of Object
Module inherits from Object                        Up
Class inherits from Module
How Ruby walks hierarchy to find methods?           Up
  The “Out and up” way
                                             Out
    Out = klass = object.class
    Up = super = MyClass.superclass

                                                        12
Ruby Variables
Pseudo Variables (their values can’t be changed with the assignment operator)
  self #execution context of the current method
  nil, true and false #sole-instances of NilClass, TrueClass and FalseClass
A variable can be distinguished by the characters at the start of its name.
  ‘@’ = instance variable of self.
  ‘@@’ = class variable
  ^[a-z_] = local variables
  ^[A-Z] = constant (we can change the state of the objects they reference)
  ^$ = global variables

                                                                                13
Ruby Variables - self
 it is only a reference to the current receiver
 If you omit the receiver, it defaults to self, the
 current object.
 self != this (other languages)
 self is a pseudo-variable, but it is still a variable,
 so it changes at some point, who changes the
 value of self?
   a method call
   a class/module definition




                                                          14
Ruby Variables - @ and @@
                   class variables (@@)
                     A class variable is shared among all
                     instances of a class and must be initialized
                     before they are used.
                     Example.class_v
                   class instance variables (@)
                     aka instance variables (wrong)
                     Example.class_instance_variable
                   instance variables (@)
                     Each instance of a class has a unique set of
                     instance variables
                     Example.new.iv
                                                                    15
Ruby Variables - accessors
                  accessors are Module methods
                  << is a way to access singleton classes (meta-
                  classes), in this case, we’re accessing the self’s
                  singleton class, which means AccessorsStudy
                  If we send a message to AccessorsStudy class,
                  the Ruby Interpreter uses the “out and up” way
                  to find methods.
                    AccessorsStudy.read_class_iv
                    AccessorsStudy -----> [<AccessorsStudy>]




                                                                       16
Ruby Methods
               Instance methods
                 we don’t specify the receiver, so it’s
                 self, which means the current instance
               Class methods
                 They don’t even exist, they are
                 singleton methods, because they are in
                 a singleton class
                 In this case we have 3 singleton
                 methods but Ruby only creates one
                 singleton class, hence the name.




                                                          17
Ruby Methods - object methods
                object-specific singleton classes




                                             Object




                   message
                  value = “”
                                             String
                klass = String           super = Object

                                                          18
Ruby Methods - object methods
                object-specific singleton classes

                                             Object




                                             String
                                         super = Object



                  message                   Singleton
                  value = “”              super = String
                klass = Singleton         methods: /, first

                                                             19
Ruby Methods - object creation
                  obj = Object.new
                    creates a blank object and calls the
                    initialize method
                  initialize method
                    initializes the object (variables, etc)
                  super
                    The call to super can access a
                    parent’s method regardless of its
                    visibility, that allows the subclass to
                    override its parent’s visibility rules
                    (X_o), believe it or not.

                                                              20
Ruby Methods - Access control
Ruby defines 3 levels of protection for module and class constants and
methods:
  Public: accessible to anyone. Methods are public by default (except for
  initialize, which is always private).
  Protected: Can be invoked only by objects of the defining class and its
  subclasses. Access is kept within the family.
  Private: Can be called only in functional form (that is, with an implicit self
  as the receiver). Private methods therefore can be called only in the
  defining class and by direct descendants within the same object.
You specify access levels to methods within class or module definitions
using one or more of the three functions public, protected, and private

                                                                                   21
Ruby Methods - Access control
                            protected level:

                                if you want one
                                instance of a certain
                                class to do something
                                with another instance
                                of its class.

                            private level

                                you don’t want the
                                instances to access
                                some methods of its
                                class

                            public level

                                you want methods to
                                be accessed from the
                                outside world.
                                                        22
Last but not least - Top level
The top-level default object, main, which is an
instance of Object brought into being
automatically for the sole reason that
something has to be self, even at the top level.
A method that you define at the top level is
stored as a private instance method of the
Object class.
Methods defined in Object are visible to all
objects




                                                   23
The End

raf.magana@gmail.com

                       24

Contenu connexe

Tendances

Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptUsman Mehmood
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS ImplimentationUsman Mehmood
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionOregon FIRST Robotics
 
Lightning talk
Lightning talkLightning talk
Lightning talknpalaniuk
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...roxlu
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objectskhaliledapal
 

Tendances (20)

CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Java
JavaJava
Java
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introduction
 
Lightning talk
Lightning talkLightning talk
Lightning talk
 
Java
JavaJava
Java
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Oop java
Oop javaOop java
Oop java
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objects
 

Similaire à The Ruby Object Model by Rafael Magana

Aman kingrubyoo pnew
Aman kingrubyoo pnew Aman kingrubyoo pnew
Aman kingrubyoo pnew ThoughtWorks
 
Ruby OOP: Objects over Classes
Ruby OOP: Objects over ClassesRuby OOP: Objects over Classes
Ruby OOP: Objects over ClassesAman King
 
Intro Ruby Classes Part I
Intro Ruby Classes Part IIntro Ruby Classes Part I
Intro Ruby Classes Part IJuan Leal
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxethiouniverse
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Christopher Haupt
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Fresherszynofustechnology
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview QuestionsSumanth krishna
 
Ruby's metaclass
Ruby's metaclassRuby's metaclass
Ruby's metaclassxds2000
 
Paca oops slid
Paca oops slidPaca oops slid
Paca oops slidpacatarpit
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questionsDhivyashree Selvarajtnkpm
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingWei Jen Lu
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorialGhulam Abbas Khan
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Java Basics Presentation
Java Basics PresentationJava Basics Presentation
Java Basics PresentationOmid Sohrabi
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questionsMehtaacademy
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxDaveEstonilo
 

Similaire à The Ruby Object Model by Rafael Magana (20)

Aman kingrubyoo pnew
Aman kingrubyoo pnew Aman kingrubyoo pnew
Aman kingrubyoo pnew
 
Ruby OOP: Objects over Classes
Ruby OOP: Objects over ClassesRuby OOP: Objects over Classes
Ruby OOP: Objects over Classes
 
Intro Ruby Classes Part I
Intro Ruby Classes Part IIntro Ruby Classes Part I
Intro Ruby Classes Part I
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Freshers
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview Questions
 
Ruby's metaclass
Ruby's metaclassRuby's metaclass
Ruby's metaclass
 
Paca oops slid
Paca oops slidPaca oops slid
Paca oops slid
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questions
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorial
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Metaprogramming ruby
Metaprogramming rubyMetaprogramming ruby
Metaprogramming ruby
 
Java Simple Notes
Java Simple NotesJava Simple Notes
Java Simple Notes
 
Java Basics Presentation
Java Basics PresentationJava Basics Presentation
Java Basics Presentation
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questions
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptx
 
Java basics
Java basicsJava basics
Java basics
 

Dernier

Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
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 productivityPrincipled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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 Processorsdebabhi2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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 RobisonAnna Loughnan Colquhoun
 
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 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
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 educationjfdjdjcjdnsjd
 
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 AutomationSafe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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, ...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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 FMESafe Software
 
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...Drew Madelung
 

Dernier (20)

Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
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
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
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...
 

The Ruby Object Model by Rafael Magana

  • 1. Ruby The (good) compulsive obsession for the objects (or the object of obsession) An introduction to the Ruby Object Model raf.magana@gmail.com 1
  • 2. What you will find in this presentation OOP concepts Definition of object Ruby Objects Ruby Classes Objects and classes interaction Ruby Modules Ruby and Meta-programming Ruby Variables Ruby Methods The Top Level 2
  • 3. OOP concepts Inheritance It allows a class to have the same behavior as another class Ruby uses < (less than) for inheritance: class Human < Mammal The default parent class is Object Encapsulation To modify an object's state, one of the object's behaviors must be used In “my_object.something”, “something” must be a method, not a variable Polymorphism It allows two or more objects respond to the same message person.wake_up / computer.wake_up / animal.wake_up 3
  • 4. Object? what is that? The OOP definition: Object = state + behavior state is described by variables (attributes) behavior is described by methods Every object of the same type will have its own state All the objects of the same type will share the same behavior 4
  • 5. Ruby Objects A Ruby object consist of the following A reference to the object immediate class (interpreter stores this in ‘klass’) A hash table of instance variables Objects does not have a table of methods, they are in the class. Only classes can have methods. A set of flags: Singleton, Mark, Finalize, Taint, Exivar, Freeze, etc. 5
  • 6. Ruby Classes (get ready to become insane) A Ruby class: it’s an instance object of class Class, an consists of the following: A reference to the object immediate class (interpreter stores this in ‘klass’) A hash table of instance variables A hash table of methods A set of flags: Singleton, Mark, Finalize, Taint, Exivar, Freeze, etc. A reference to the superclass (interpreter stores it in “super”) my_object.class denotes "instance of" (my_object = MyClass.new) MyClass.superclass denotes "inherits from" ( MyClass < OtherClass) In Ruby, always remember this, CLASSES ARE OBJECTS!!! 6
  • 7. Ruby Classes since classes are objects, class objects are instances of other class “but, if classes are objects, and you just said objects doesn’t have methods, only classes does, so what’s going on here?”, you’d say. well, I have to say that a class isn’t really an object (x_X) look at the following code taken from the Ruby source but a class is still an object: * you can store instance variables * inherits from the Object class 7
  • 8. Ruby Classes In Ruby there are two types of classes “Real” classes and “meta”-classes (singleton, virtual, Eigen or ghost classes) What is the difference? “meta”-classes are “Real” classes with a flag set to ‘virtual’ a “meta”-class is created as needed and inserted in the inheritance chain before the object "real" class and they are hidden. What are meta-classes useful for? If the instance methods of my_object are in MyClass and MyClass is an instance of class Class, so it can’t have its own instance methods, then where are the instance methods of MyClass object? The instance methods of MyClass object are in a meta-class, a Singleton class. 8
  • 9. How classes and instances interact Every method call nominate a receiver and a message. “my_obj.my_method”: my_obj is the receiver and my_method is the message. my_guitar = receiver; dup/play = message Guitar = receiver; strings = message 9
  • 10. Ruby modules A Ruby module is an object that acts as a placeholder for classes, methods and constants. A module is like a class with 3 key differences It isn’t a class, (but it is an object and it has instance methods), Module is actually the superclass of Class - class Class < Module It cannot be instantiated (you cannot do x = MyModule.new) It can be mixed in a class to enhance its possibilities A module can be two things A namespace, a way to regroup similar things. A Mixin (mixed in), they eliminate the need of multiple inheritance 10
  • 11. Ruby Modules As a namespace As a Mixin Kernel#require loads an external file Module#include Module#append_features it makes a reference from the class to the included module 11
  • 12. Hierarchy diagram Kernel is a module, not a class Object class mixes in the Kernel module it defines the instance methods of Object Module inherits from Object Up Class inherits from Module How Ruby walks hierarchy to find methods? Up The “Out and up” way Out Out = klass = object.class Up = super = MyClass.superclass 12
  • 13. Ruby Variables Pseudo Variables (their values can’t be changed with the assignment operator) self #execution context of the current method nil, true and false #sole-instances of NilClass, TrueClass and FalseClass A variable can be distinguished by the characters at the start of its name. ‘@’ = instance variable of self. ‘@@’ = class variable ^[a-z_] = local variables ^[A-Z] = constant (we can change the state of the objects they reference) ^$ = global variables 13
  • 14. Ruby Variables - self it is only a reference to the current receiver If you omit the receiver, it defaults to self, the current object. self != this (other languages) self is a pseudo-variable, but it is still a variable, so it changes at some point, who changes the value of self? a method call a class/module definition 14
  • 15. Ruby Variables - @ and @@ class variables (@@) A class variable is shared among all instances of a class and must be initialized before they are used. Example.class_v class instance variables (@) aka instance variables (wrong) Example.class_instance_variable instance variables (@) Each instance of a class has a unique set of instance variables Example.new.iv 15
  • 16. Ruby Variables - accessors accessors are Module methods << is a way to access singleton classes (meta- classes), in this case, we’re accessing the self’s singleton class, which means AccessorsStudy If we send a message to AccessorsStudy class, the Ruby Interpreter uses the “out and up” way to find methods. AccessorsStudy.read_class_iv AccessorsStudy -----> [<AccessorsStudy>] 16
  • 17. Ruby Methods Instance methods we don’t specify the receiver, so it’s self, which means the current instance Class methods They don’t even exist, they are singleton methods, because they are in a singleton class In this case we have 3 singleton methods but Ruby only creates one singleton class, hence the name. 17
  • 18. Ruby Methods - object methods object-specific singleton classes Object message value = “” String klass = String super = Object 18
  • 19. Ruby Methods - object methods object-specific singleton classes Object String super = Object message Singleton value = “” super = String klass = Singleton methods: /, first 19
  • 20. Ruby Methods - object creation obj = Object.new creates a blank object and calls the initialize method initialize method initializes the object (variables, etc) super The call to super can access a parent’s method regardless of its visibility, that allows the subclass to override its parent’s visibility rules (X_o), believe it or not. 20
  • 21. Ruby Methods - Access control Ruby defines 3 levels of protection for module and class constants and methods: Public: accessible to anyone. Methods are public by default (except for initialize, which is always private). Protected: Can be invoked only by objects of the defining class and its subclasses. Access is kept within the family. Private: Can be called only in functional form (that is, with an implicit self as the receiver). Private methods therefore can be called only in the defining class and by direct descendants within the same object. You specify access levels to methods within class or module definitions using one or more of the three functions public, protected, and private 21
  • 22. Ruby Methods - Access control protected level: if you want one instance of a certain class to do something with another instance of its class. private level you don’t want the instances to access some methods of its class public level you want methods to be accessed from the outside world. 22
  • 23. Last but not least - Top level The top-level default object, main, which is an instance of Object brought into being automatically for the sole reason that something has to be self, even at the top level. A method that you define at the top level is stored as a private instance method of the Object class. Methods defined in Object are visible to all objects 23