Sunday, 10 April 2011

Ruby: metaprogramming

Definitions
Singleton method: a method defined on a particular object
Singleton class: the anonymous class created in which a singleton method is defined

Object Model
  • Instance variables live in objects, and methods live in classes.
    • You can get a list of object's methods by calling obj.methods.
    • For a class, you can call klass.methods to see what class methods are available, and klass.instance_methods to know the instance methods. klass.instance_methods(false) returns methods defined by the class and not inherited.
  • Classes themselves are nothing but objects, and have their own class called Class.
    • All classes ultimately inherit from Object.
      "hello".class # => String
      String.class # => Class
      Class.instance_methods(false) # => [:allocate, :new, :superclass]
      # :superclass is only a method a class, not an object. 
      String.superclass # => Object
      
  • The methods of an a class are the instance methods of Class.
Self
  • Every line of Ruby code is executed inside an object - the so-called current object. The current object is also known as self.
  •  In a class or module definition, the role of self is taken by the class or module.
Singleton Methods
  • Class methods are Singleton Methods of a class.
  • Introspection methods:
    • singleton_methods returns all the singleton methods for the object (also the ones in included modules).
    • singleton_methods(false) returns all the singleton methods for the object, but not those declared in included modules.
    • methods(false) supposedly returns the singleton methods by calling singleton_methods, but it also passes the parameter false to it.
      String.methods(false) == String.singleton_methods(false) # => true

No comments :

Post a Comment