SlideShare a Scribd company logo
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
Ruby object model
   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.
Ruby object model
 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"
Ruby object model
   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.
Ruby object model
   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
Ruby object model
Ruby object model
   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.
Ruby object model
   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 object model
   Ruby supports only single inheritance.
   Classes can import modules as mixins.
   The class Object is almost at the top of the
    inheritance chart.
Ruby object model
• 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.
Ruby object model
   The top-level method is stored as a private
    instance method of the Object class.
Ruby object model
   Every object is “born” with certain innate
    abilities.
     object_id
     respond_to?
     send
     methods
     instance_variables
Ruby object model
   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.
Ruby object model
   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
Ruby object model
Ruby object model
   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.
Ruby object model
   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
Ruby object model
   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.
Ruby object model
   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
Ruby object model
   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.”
Ruby object model
   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.
Ruby object model
Ruby object model
   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.
Ruby object model
Ruby object model
   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.
Ruby object model
Ruby object model
   Provides a storage mechanism shared
    between a class and its instances.
   Visible only to a class and its instances.
Ruby object model
   They’re class-hierarchy variables.
Ruby object model
Ruby object model
   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.
Ruby object model
Ruby object model
   The Well-Grounded Rubyist, David A. Black
   Metaprogramming Ruby, Paolo Perrotta

More Related Content

Viewers also liked (19)

PPTX
Ruby OOP: Objects over Classes
Aman King
 
PDF
Ruby's Object Model: Metaprogramming and other Magic
Burke Libbey
 
PDF
Designing Ruby APIs
Wen-Tien Chang
 
PDF
DevNexus 2017 - Building and Deploying 12 Factor Apps in Scala, Java, Ruby, a...
Neil Shannon
 
KEY
MongoDB - Ruby document store that doesn't rhyme with ouch
Wynn Netherland
 
PPSX
Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.
IT-Доминанта
 
PDF
Object-Oriented BDD w/ Cucumber by Matt van Horn
Solano Labs
 
PDF
HTML Lecture Part 1 of 2
Sharon Wasden
 
PPTX
The Black Magic of Ruby Metaprogramming
itnig
 
PDF
Elasticsearch Basics
Shifa Khan
 
PPT
Ruby For Java Programmers
Mike Bowler
 
PDF
Ruby on Rails for beginners
Vysakh Sreenivasan
 
PDF
OOP Intro in Ruby for NHRuby Feb 2010
bturnbull
 
PDF
Ruby everywhere
yukihiro_matz
 
PDF
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
peter_marklund
 
PDF
How to Teach Yourself to Code
Mattan Griffel
 
PDF
Ruby for Java Developers
Robert Reiz
 
Ruby OOP: Objects over Classes
Aman King
 
Ruby's Object Model: Metaprogramming and other Magic
Burke Libbey
 
Designing Ruby APIs
Wen-Tien Chang
 
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
Wynn Netherland
 
Основные понятия связанные с разработкой ПО: просто о сложном. Лаабе Дмитрий.
IT-Доминанта
 
Object-Oriented BDD w/ Cucumber by Matt van Horn
Solano Labs
 
HTML Lecture Part 1 of 2
Sharon Wasden
 
The Black Magic of Ruby Metaprogramming
itnig
 
Elasticsearch Basics
Shifa Khan
 
Ruby For Java Programmers
Mike Bowler
 
Ruby on Rails for beginners
Vysakh Sreenivasan
 
OOP Intro in Ruby for NHRuby Feb 2010
bturnbull
 
Ruby everywhere
yukihiro_matz
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
peter_marklund
 
How to Teach Yourself to Code
Mattan Griffel
 
Ruby for Java Developers
Robert Reiz
 

Similar to Ruby object model (20)

PDF
Metaprogramming in Ruby
Nicolò Calcavecchia
 
PPTX
Ruby :: Training 1
Pavel Tyk
 
PPT
Ruby for C# Developers
Cory Foy
 
PDF
Ruby training day1
Bindesh Vijayan
 
ODP
Ruby Basics by Rafiq
Rafiqdeen
 
PDF
Introduction to Ruby Programming Language
Nicolò Calcavecchia
 
PDF
05 ruby classes
Walker Maidana
 
DOCX
Ruby Interview Questions
Sumanth krishna
 
PPTX
Rubyconf Bangladesh 2017 - Lets start coding in Ruby
Ruby Bangladesh
 
PDF
A limited guide to intermediate and advanced Ruby
Vysakh Sreenivasan
 
PDF
RubyMiniGuide-v1.0_0
tutorialsruby
 
PDF
RubyMiniGuide-v1.0_0
tutorialsruby
 
PPTX
Introduction to Ruby’s Reflection API
Niranjan Sarade
 
PPTX
Ruby Basics
NagaLakshmi_N
 
PPTX
Code for Startup MVP (Ruby on Rails) Session 2
Henry S
 
PPTX
7 Methods and Functional Programming
Deepak Hagadur Bheemaraju
 
PPT
Metaprogramming With Ruby
Farooq Ali
 
PPTX
Deciphering the Ruby Object Model
Karthik Sirasanagandla
 
PPT
name name2 n2.ppt
callroom
 
PPT
name name2 n
callroom
 
Metaprogramming in Ruby
Nicolò Calcavecchia
 
Ruby :: Training 1
Pavel Tyk
 
Ruby for C# Developers
Cory Foy
 
Ruby training day1
Bindesh Vijayan
 
Ruby Basics by Rafiq
Rafiqdeen
 
Introduction to Ruby Programming Language
Nicolò Calcavecchia
 
05 ruby classes
Walker Maidana
 
Ruby Interview Questions
Sumanth krishna
 
Rubyconf Bangladesh 2017 - Lets start coding in Ruby
Ruby Bangladesh
 
A limited guide to intermediate and advanced Ruby
Vysakh Sreenivasan
 
RubyMiniGuide-v1.0_0
tutorialsruby
 
RubyMiniGuide-v1.0_0
tutorialsruby
 
Introduction to Ruby’s Reflection API
Niranjan Sarade
 
Ruby Basics
NagaLakshmi_N
 
Code for Startup MVP (Ruby on Rails) Session 2
Henry S
 
7 Methods and Functional Programming
Deepak Hagadur Bheemaraju
 
Metaprogramming With Ruby
Farooq Ali
 
Deciphering the Ruby Object Model
Karthik Sirasanagandla
 
name name2 n2.ppt
callroom
 
name name2 n
callroom
 
Ad

More from Chamnap Chhorn (7)

PDF
Introduction to rails
Chamnap Chhorn
 
PDF
High performance website
Chamnap Chhorn
 
PPTX
Rest and Rails
Chamnap Chhorn
 
PPTX
Introduction to Web Architecture
Chamnap Chhorn
 
PPT
Principles in Refactoring
Chamnap Chhorn
 
PPTX
JavaScript in Object-Oriented Way
Chamnap Chhorn
 
PPT
Rest in Rails
Chamnap Chhorn
 
Introduction to rails
Chamnap Chhorn
 
High performance website
Chamnap Chhorn
 
Rest and Rails
Chamnap Chhorn
 
Introduction to Web Architecture
Chamnap Chhorn
 
Principles in Refactoring
Chamnap Chhorn
 
JavaScript in Object-Oriented Way
Chamnap Chhorn
 
Rest in Rails
Chamnap Chhorn
 
Ad

Recently uploaded (20)

PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 

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
  • 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.
  • 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"
  • 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.
  • 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
  • 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.
  • 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.
  • 33. Ruby supports only single inheritance.  Classes can import modules as mixins.  The class Object is almost at the top of the inheritance chart.
  • 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.
  • 38. The top-level method is stored as a private instance method of the Object class.
  • 40. Every object is “born” with certain innate abilities.  object_id  respond_to?  send  methods  instance_variables
  • 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.
  • 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
  • 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.
  • 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
  • 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.
  • 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
  • 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.”
  • 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.
  • 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.
  • 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.
  • 90. Provides a storage mechanism shared between a class and its instances.  Visible only to a class and its instances.
  • 92. They’re class-hierarchy variables.
  • 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.
  • 100. The Well-Grounded Rubyist, David A. Black  Metaprogramming Ruby, Paolo Perrotta