SlideShare una empresa de Scribd logo
1 de 17
Introduction to Ruby’s Reflection API
                             - Niranjan Sarade
Reflection

a.k.a. Introspection

A program can examine its state and structure

A program can alter its state and structure

Ruby’s reflection API is rich and most of the methods are defined by Kernel,
Object and Module
Determine type of an object

o.class #=> Returns the class of an object c

c.superclass #=> Returns the superclass of a class c

o.instance_of? c #=> Determines whether the object o.class == c

o.is_a? c or o.kind_of? c
#=> determines o is an instance of c or any of its subclasses. If c is a module, then this
    method tests whether o.class (or any of its ancestors) includes this module.

c === o
#=> For any class or module c, determines if o.is_a?(c)

o.respond_to? Name
#=> Determines whether the object has public or protected method with the specified
    name. Pass true as 2nd parameter to check private methods as well
module C
end

class A
 include C
end

class B < A
end

a = A.new
a.instance_of?(A) #=> true

b = B.new
b.instance_of?(B) #=> true
b.instance_of?(A) #=> false #=> instance_of? does not check inheritence

b.is_a?(A) #=> true
b.is_a?(B) #=> true
b.is_a?(C) #=> true

B.is_a?(A) #=> false
A.is_a?(A) #=> false
o = “niranjan”

o.class #=> String

o.class.superclass #=> Object

o.class.superclass.superclass #=> nil : Object has no superclass



# Ruby 1.9 only

Object.superclass #=> BasicObject

BasicObject.superclass #=> nil
Ancestors of class or module
module A; end
module B; include A; end
class C; include B; end

C < B #=> true : C includes B
B < A #=> true
C < A #=> true
String < Numeric #=> nil: strings are not numbers

A.ancestors #=> [A]
B.ancestors #=> [B, A]
C.ancestors #=> [C, B, A, Object, Kernel]
String.ancestors #=> [String, Comparable, Object, Kernel]

C.include?(B) #=> true (public instance method defined by the Module class)
C.include?(A) #=> true
B.include?(A) #=> true
A.include?(A) #=> false
A.include?(B) #=> false

A.included_modules #=> [ ]
B.included_modules #=> [A]
C.included_modules #=> [B, A, Kernel]
Module.nesting

module M
   class C
             Module.nesting #=> [M::C, M]
      end
end

The class method Module.nesting returns nesting of modules at the current
location.

Module.nesting[0] => current class or module

Module.nesting[1] => containing class or module
Variables and Constants

- global_variables

- local_variables

- instance_variables

- class_variables

- constants

These methods except local_variables return array of strings in Ruby 1.8 and
array of symbols in Ruby 1.9.

The local_variables method returns an array of strings in both versions of Ruby.
Querying, setting, removing and testing variables

Local variables :-
x=1
eval(“x”) #=> 1
eval(“x = 2”)
eval(“x”)

Instance variables :-
o = Object.new
o.instance_variable_set(:@x, 10)
o.instance_variable_get(:@x) #=> 10
o.instance_variable_defined?(:@x) #=> true

Class variables :-
Object.class_variable_set(:@@x, 5) #=> Private in Ruby 1.8
Object.class_variable_get(:@@x) #=> 5 ; Private in Ruby 1.8
Object.class_variable_defined?(:@@x) #=> true; Ruby 1.9 and later
Continued…

Constants :-
Math.const_set(:EPI, Math::E*Math::PI)
Math.const_get(:EPI) #=> 8.539…
Math.const_defined? :EPI #=> true

In Ruby 1.9, we can pass ‘false’ as 2nd argument to const_get and const_defined?
to specify that these methods should only look at the current class or module and should
not consider inherited constants.

Object and Module define private methods for undefining instance variables, class
variables and constants. (Use eval or send to invoke these methods)

They return the value of the removed variable or constant.

o.instance_eval {remove_instance_variable(:@x)}
String.class_eval {remove_class_variable (:@@x)}
Math.send :remove_const, :EPI
Listing and testing methods

o = “test”
o.methods #=> [ names of all public methods ]
o.public_methods #=> same as above
o.public_methods(false) #=> Exclude inherited methods
o.protected_methods #=> [ ]
o.private_methods #=> array of all private methods
o.private_methods(false) #=> Exclude inherited private methods
def o.single; 1; end # define a singleton method
o.singleton_methods #=> *“single”+

String.instance_methods == “s”.public_methods #=> true
String.instance_methods(false) == “s”.public_methods(false) #=> true
String.public_instance_methods == String.instance_methods #=> true
String.protected_instance_methods #=> []
String.private_instance_methods(false) #=> *“initialize_copy”, “initialize”+

The class methods of a class or module are singleton methods of the Class or Module object. So to list
the class methods, use Object.singleton_methods:

Math.singleton_methods #=> *“acos”, “log10”, …+
Define, undefine and alias methods

define_method –> private instance method of Module class

# add an instance method names m to class c with body b

def add_method(c,m,&b)
    c.class_eval {
           define_method(m,&b)
    }
end

add_method(String, :greet) ,‘Hello’ + self-

‘world’.greet #=> ‘Hello world’

To create a synonym or an alias for an existing method :-

alias plus + # make plus a synonym for the + operator (2 identifiers to be hardcoded)

Or

alias_method # private instance method of Module class (dynamic programming)
Continued…

undef method_name

remove_method or undef _method => private methods of Module class

remove_method removes the definition of the method from the current class
If there is a version defined by a superclass, that version now will be inherited.

undef_method prevents any invocation of the specified method through an
instance of the class, even if there is an inherited version of that method.
Aliasing

A more practical reason for aliasing methods is to insert new functionality into a
method – augmenting existing methods

def hello
    p ‘hello’
end

alias original_hello hello

def hello
    p ‘some stuff’
    original_hello
    p ‘some more stuff’
end
Method lookup or method name resolution algorithm
For method invocation expression o.m, Ruby performs name resolution with the following
steps :-

1.    First, it checks the eigenclass of o for singleton methods named m
2.    If no method m is found in the eigenclass, ruby searches the class of o for an instance
      method named m
3.    If not found, ruby searches the instance methods of any modules included by the class of
      o. If that class includes more than one module, then they are searched in the reverse of
      the order in which they were included. i.e. the most recently included module is searched
      first.
4.    If not found, then the search moves up the inheritance hierarchy to the superclass. Steps 2
      and 3 are repeated for each class in the inheritance hierarchy until each ancestor class and
      its included modules have been searched.
5.    If not found, then method_missing is invoked instead. In order to find an appropriate
      definition of this method, the name resolution algorithm starts over at step 1. The Kernel
      module provides a default implementation of method_missing, so this second pass of
      name resolution is guaranteed to succeed.
6.    This may seem like it requires ruby to perform an exhaustive search every time it invokes a
      method.
7.    However, successful method lookups will be cached so that subsequent lookups of the
      same name will be very quick.
e.g. “hello”.world

1.   Check the eigenclass for singleton methods.

2.   Check the String class. There is no instance method named ‘world’.

3.   Check the Comparable and Enumerable modules of the String class for an instance method
     named ‘world’.

4.   Check the superclass of String, which is Object.

5.   Look for method_missing in each of the spots above. The first definition of
     method_missing we find id in the Kernel module, so this method gets invoked.

6.   It raises an exception NoMethodError : undefined method ‘world’ for “hello”:String.

7.   However, successful method lookups will be cached so that subsequent lookups of the
     same name will be very quick.
Thank you !

Más contenido relacionado

La actualidad más candente

Java Reflection Explained Simply
Java Reflection Explained SimplyJava Reflection Explained Simply
Java Reflection Explained Simply
Ciaran McHale
 
Reflection in java
Reflection in javaReflection in java
Reflection in java
upen.rockin
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
Terry Yoast
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 

La actualidad más candente (20)

Java Reflection Explained Simply
Java Reflection Explained SimplyJava Reflection Explained Simply
Java Reflection Explained Simply
 
Reflection in java
Reflection in javaReflection in java
Reflection in java
 
Java Reflection @KonaTechAdda
Java Reflection @KonaTechAddaJava Reflection @KonaTechAdda
Java Reflection @KonaTechAdda
 
Reflection in Java
Reflection in JavaReflection in Java
Reflection in Java
 
Java reflection
Java reflectionJava reflection
Java reflection
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 

Similar a Introduction to Ruby’s Reflection API

RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 

Similar a Introduction to Ruby’s Reflection API (20)

Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Hemajava
HemajavaHemajava
Hemajava
 
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
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
Python_Unit_3.pdf
Python_Unit_3.pdfPython_Unit_3.pdf
Python_Unit_3.pdf
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Only oop
Only oopOnly oop
Only oop
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Python3
Python3Python3
Python3
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Introduction to ruby eval
Introduction to ruby evalIntroduction to ruby eval
Introduction to ruby eval
 
The Ring programming language version 1.5.1 book - Part 70 of 180
The Ring programming language version 1.5.1 book - Part 70 of 180The Ring programming language version 1.5.1 book - Part 70 of 180
The Ring programming language version 1.5.1 book - Part 70 of 180
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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...
 
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...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 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
 
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
 
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
 

Introduction to Ruby’s Reflection API

  • 1. Introduction to Ruby’s Reflection API - Niranjan Sarade
  • 2. Reflection a.k.a. Introspection A program can examine its state and structure A program can alter its state and structure Ruby’s reflection API is rich and most of the methods are defined by Kernel, Object and Module
  • 3. Determine type of an object o.class #=> Returns the class of an object c c.superclass #=> Returns the superclass of a class c o.instance_of? c #=> Determines whether the object o.class == c o.is_a? c or o.kind_of? c #=> determines o is an instance of c or any of its subclasses. If c is a module, then this method tests whether o.class (or any of its ancestors) includes this module. c === o #=> For any class or module c, determines if o.is_a?(c) o.respond_to? Name #=> Determines whether the object has public or protected method with the specified name. Pass true as 2nd parameter to check private methods as well
  • 4. module C end class A include C end class B < A end a = A.new a.instance_of?(A) #=> true b = B.new b.instance_of?(B) #=> true b.instance_of?(A) #=> false #=> instance_of? does not check inheritence b.is_a?(A) #=> true b.is_a?(B) #=> true b.is_a?(C) #=> true B.is_a?(A) #=> false A.is_a?(A) #=> false
  • 5. o = “niranjan” o.class #=> String o.class.superclass #=> Object o.class.superclass.superclass #=> nil : Object has no superclass # Ruby 1.9 only Object.superclass #=> BasicObject BasicObject.superclass #=> nil
  • 6. Ancestors of class or module module A; end module B; include A; end class C; include B; end C < B #=> true : C includes B B < A #=> true C < A #=> true String < Numeric #=> nil: strings are not numbers A.ancestors #=> [A] B.ancestors #=> [B, A] C.ancestors #=> [C, B, A, Object, Kernel] String.ancestors #=> [String, Comparable, Object, Kernel] C.include?(B) #=> true (public instance method defined by the Module class) C.include?(A) #=> true B.include?(A) #=> true A.include?(A) #=> false A.include?(B) #=> false A.included_modules #=> [ ] B.included_modules #=> [A] C.included_modules #=> [B, A, Kernel]
  • 7. Module.nesting module M class C Module.nesting #=> [M::C, M] end end The class method Module.nesting returns nesting of modules at the current location. Module.nesting[0] => current class or module Module.nesting[1] => containing class or module
  • 8. Variables and Constants - global_variables - local_variables - instance_variables - class_variables - constants These methods except local_variables return array of strings in Ruby 1.8 and array of symbols in Ruby 1.9. The local_variables method returns an array of strings in both versions of Ruby.
  • 9. Querying, setting, removing and testing variables Local variables :- x=1 eval(“x”) #=> 1 eval(“x = 2”) eval(“x”) Instance variables :- o = Object.new o.instance_variable_set(:@x, 10) o.instance_variable_get(:@x) #=> 10 o.instance_variable_defined?(:@x) #=> true Class variables :- Object.class_variable_set(:@@x, 5) #=> Private in Ruby 1.8 Object.class_variable_get(:@@x) #=> 5 ; Private in Ruby 1.8 Object.class_variable_defined?(:@@x) #=> true; Ruby 1.9 and later
  • 10. Continued… Constants :- Math.const_set(:EPI, Math::E*Math::PI) Math.const_get(:EPI) #=> 8.539… Math.const_defined? :EPI #=> true In Ruby 1.9, we can pass ‘false’ as 2nd argument to const_get and const_defined? to specify that these methods should only look at the current class or module and should not consider inherited constants. Object and Module define private methods for undefining instance variables, class variables and constants. (Use eval or send to invoke these methods) They return the value of the removed variable or constant. o.instance_eval {remove_instance_variable(:@x)} String.class_eval {remove_class_variable (:@@x)} Math.send :remove_const, :EPI
  • 11. Listing and testing methods o = “test” o.methods #=> [ names of all public methods ] o.public_methods #=> same as above o.public_methods(false) #=> Exclude inherited methods o.protected_methods #=> [ ] o.private_methods #=> array of all private methods o.private_methods(false) #=> Exclude inherited private methods def o.single; 1; end # define a singleton method o.singleton_methods #=> *“single”+ String.instance_methods == “s”.public_methods #=> true String.instance_methods(false) == “s”.public_methods(false) #=> true String.public_instance_methods == String.instance_methods #=> true String.protected_instance_methods #=> [] String.private_instance_methods(false) #=> *“initialize_copy”, “initialize”+ The class methods of a class or module are singleton methods of the Class or Module object. So to list the class methods, use Object.singleton_methods: Math.singleton_methods #=> *“acos”, “log10”, …+
  • 12. Define, undefine and alias methods define_method –> private instance method of Module class # add an instance method names m to class c with body b def add_method(c,m,&b) c.class_eval { define_method(m,&b) } end add_method(String, :greet) ,‘Hello’ + self- ‘world’.greet #=> ‘Hello world’ To create a synonym or an alias for an existing method :- alias plus + # make plus a synonym for the + operator (2 identifiers to be hardcoded) Or alias_method # private instance method of Module class (dynamic programming)
  • 13. Continued… undef method_name remove_method or undef _method => private methods of Module class remove_method removes the definition of the method from the current class If there is a version defined by a superclass, that version now will be inherited. undef_method prevents any invocation of the specified method through an instance of the class, even if there is an inherited version of that method.
  • 14. Aliasing A more practical reason for aliasing methods is to insert new functionality into a method – augmenting existing methods def hello p ‘hello’ end alias original_hello hello def hello p ‘some stuff’ original_hello p ‘some more stuff’ end
  • 15. Method lookup or method name resolution algorithm For method invocation expression o.m, Ruby performs name resolution with the following steps :- 1. First, it checks the eigenclass of o for singleton methods named m 2. If no method m is found in the eigenclass, ruby searches the class of o for an instance method named m 3. If not found, ruby searches the instance methods of any modules included by the class of o. If that class includes more than one module, then they are searched in the reverse of the order in which they were included. i.e. the most recently included module is searched first. 4. If not found, then the search moves up the inheritance hierarchy to the superclass. Steps 2 and 3 are repeated for each class in the inheritance hierarchy until each ancestor class and its included modules have been searched. 5. If not found, then method_missing is invoked instead. In order to find an appropriate definition of this method, the name resolution algorithm starts over at step 1. The Kernel module provides a default implementation of method_missing, so this second pass of name resolution is guaranteed to succeed. 6. This may seem like it requires ruby to perform an exhaustive search every time it invokes a method. 7. However, successful method lookups will be cached so that subsequent lookups of the same name will be very quick.
  • 16. e.g. “hello”.world 1. Check the eigenclass for singleton methods. 2. Check the String class. There is no instance method named ‘world’. 3. Check the Comparable and Enumerable modules of the String class for an instance method named ‘world’. 4. Check the superclass of String, which is Object. 5. Look for method_missing in each of the spots above. The first definition of method_missing we find id in the Kernel module, so this method gets invoked. 6. It raises an exception NoMethodError : undefined method ‘world’ for “hello”:String. 7. However, successful method lookups will be cached so that subsequent lookups of the same name will be very quick.