<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Ssgujar</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Ssgujar"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Ssgujar"/>
	<updated>2026-05-13T03:25:28Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=62858</id>
		<title>CSC/ECE 517 Fall 2012</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=62858"/>
		<updated>2012-09-06T00:05:03Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: Created page with &amp;quot; *CSC/ECE 517 Fall 2012/ch1 n xx&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 n xx]]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=MainPage&amp;diff=62857</id>
		<title>MainPage</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=MainPage&amp;diff=62857"/>
		<updated>2012-09-05T23:58:26Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;* [[CSC 216]] learning exercise&lt;br /&gt;
* [[Expertiza documentation]]&lt;br /&gt;
* [[CSC 379]]&lt;br /&gt;
* [[CSC/ECE 506 Fall 2007]]&lt;br /&gt;
* [[ECE506_Main_Page | CSC/ECE 506 Main Portal]]&lt;br /&gt;
* [[CSC/ECE 517 Fall 2007]]&lt;br /&gt;
* [[CSC/ECE 517 Summer 2008]]&lt;br /&gt;
* [[CSC/ECE 517 Fall 2010]]&lt;br /&gt;
* [[CSC/ECE 517 Fall 2011]]&lt;br /&gt;
* [[CSC/ECE 517 Fall 2012]]&lt;br /&gt;
* [[CSC 456 Spring 2011|CSC 456 Spring 2012]]&lt;br /&gt;
* [[Object-Oriented Design and Programming]]&lt;br /&gt;
* [[ECE 633]]&lt;br /&gt;
* [[KCU]]&lt;br /&gt;
* [[Progress reports]]&lt;br /&gt;
* [[Creating a Linux Development Environment for Expertiza - Installation Guide]]&lt;br /&gt;
* [[Using git and github for projects]]&lt;br /&gt;
* [[Using heroku to deploy your projects]]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=56597</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=56597"/>
		<updated>2011-12-14T13:51:30Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
==== Adding methods to existing classes and instances ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the square method is defined. The square method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the square method in the class Array.&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] and [http://www.ruby-doc.org/core-1.9.2/BasicObject.html#method-i-instance_eval instance_eval].&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           ## Add an instance method to class 'NewClass'&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1                                       # NoMethodError&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1                                        # &amp;quot;This is method1&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'.&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods. When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2                                       # &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2                                        # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3                                        # &amp;quot;This is method2&amp;quot; &lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method3                                       # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'.&lt;br /&gt;
&lt;br /&gt;
==== Defining new classes and attributes at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime as we saw earlier.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
==== Defining new methods for a class at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54571</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54571"/>
		<updated>2011-11-01T18:20:14Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Defining new classes and attributes at runtime */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
==== Adding methods to existing classes and instances ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] and [http://www.ruby-doc.org/core-1.9.2/BasicObject.html#method-i-instance_eval instance_eval].&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           ## Add an instance method to class 'NewClass'&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1                                       # NoMethodError&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1                                        # &amp;quot;This is method1&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'.&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods. When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2                                       # &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2                                        # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3                                        # &amp;quot;This is method2&amp;quot; &lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method3                                       # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'.&lt;br /&gt;
&lt;br /&gt;
==== Defining new classes and attributes at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime as we saw earlier.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
==== Defining new methods for a class at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54570</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54570"/>
		<updated>2011-11-01T18:19:19Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
==== Adding methods to existing classes and instances ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] and [http://www.ruby-doc.org/core-1.9.2/BasicObject.html#method-i-instance_eval instance_eval].&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           ## Add an instance method to class 'NewClass'&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1                                       # NoMethodError&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1                                        # &amp;quot;This is method1&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'.&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods. When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2                                       # &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2                                        # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3                                        # &amp;quot;This is method2&amp;quot; &lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method3                                       # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'.&lt;br /&gt;
&lt;br /&gt;
==== Defining new classes and attributes at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
==== Defining new methods for a class at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54568</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54568"/>
		<updated>2011-11-01T18:08:12Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
==== Adding methods to existing classes and instances ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are class_eval and instance_eval.&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           ## Add an instance method to class 'NewClass'&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1                                       # NoMethodError&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1                                        # &amp;quot;This is method1&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'.&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods.  When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2                                       # &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2                                        # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3                                        # &amp;quot;This is method2&amp;quot; &lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method3                                       # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'.&lt;br /&gt;
&lt;br /&gt;
==== Defining new classes and attributes at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
==== Defining new methods for a class at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54567</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54567"/>
		<updated>2011-11-01T18:07:18Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Adding method to existing classes and instances */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Adding methods to existing classes and instances ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are class_eval and instance_eval.&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           ## Add an instance method to class 'NewClass'&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1                                       # NoMethodError&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1                                        # &amp;quot;This is method1&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'.&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods.  When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2                                       # &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2                                        # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3                                        # &amp;quot;This is method2&amp;quot; &lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method3                                       # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'.&lt;br /&gt;
&lt;br /&gt;
==== Defining new classes and attributes at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
==== Defining new methods for a class at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54566</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54566"/>
		<updated>2011-11-01T18:06:59Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Adding method to existing classes and instances ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are class_eval and instance_eval.&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           ## Add an instance method to class 'NewClass'&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1                                       # NoMethodError&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1                                        # &amp;quot;This is method1&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'.&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods.  When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2                                       # &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2                                        # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3                                        # &amp;quot;This is method2&amp;quot; &lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method3                                       # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'. &lt;br /&gt;
&lt;br /&gt;
==== Defining new classes and attributes at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
==== Defining new methods for a class at runtime ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54565</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54565"/>
		<updated>2011-11-01T18:05:17Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Adding method to existing classes and instances ====&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are class_eval and instance_eval.&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           ## Add an instance method to class 'NewClass'&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1                                       # NoMethodError&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1                                        # &amp;quot;This is method1&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'.&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods.  When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2                                       # &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2                                        # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3                                        # &amp;quot;This is method2&amp;quot; &lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method3                                       # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54564</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54564"/>
		<updated>2011-11-01T18:03:06Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are class_eval and instance_eval.&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           ## Add an instance method to class 'NewClass'&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1                                       # NoMethodError&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1                                        # &amp;quot;This is method1&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'.&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods.  When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2                                       # &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2                                        # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3                                        # &amp;quot;This is method2&amp;quot; &lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method3                                       # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54563</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54563"/>
		<updated>2011-11-01T18:01:47Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are class_eval and instance_eval.&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           ## Add an instance method to class 'NewClass'&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1                                       # NoMethodError&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1                                        # &amp;quot;This is method1&amp;quot; &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'.&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods.  When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2                                       # &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2                                        # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3                                        # &amp;quot;This is method2&amp;quot; &lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method                                       # NoMethodError&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54562</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54562"/>
		<updated>2011-11-01T17:57:37Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are class_eval and instance_eval.&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
        &lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
              def method1&lt;br /&gt;
                 puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method1&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1 &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods.  When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
              def method2&lt;br /&gt;
                 puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           NewClass.method2&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2 &lt;br /&gt;
           &lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
              def method3&lt;br /&gt;
                 puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           new_obj.method3&lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54561</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54561"/>
		<updated>2011-11-01T17:54:00Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We'll look at some built-in  methods which can be used to add methods to existing classes and instances. These are class_eval and instance_eval.&lt;br /&gt;
The class_eval method is used to define instance methods. It is always used in context of a class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           NewClass.class_eval do&lt;br /&gt;
           def method1&lt;br /&gt;
           puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
           end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           NewClass.method1&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method1 &lt;br /&gt;
&lt;br /&gt;
Here, the method 'method1' is defined as an instance method. It can be invoked on an instance of the class 'NewClass'&lt;br /&gt;
&lt;br /&gt;
The instance_eval method can be used to define class methods as well as instance methods.  When used in context of a class, it generates class methods. When used in context of an instance, it generates instance methods for that particular instance only, those methods will not be generated for other instances of the same class. Let us look at an example.&lt;br /&gt;
&lt;br /&gt;
           class NewClass&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           ## Adding class method to the class 'NewClass'&lt;br /&gt;
           NewClass.instance_eval do&lt;br /&gt;
           def method2&lt;br /&gt;
            puts &amp;quot;This is method2&amp;quot;&lt;br /&gt;
           end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           NewClass.method2&lt;br /&gt;
           new_obj = NewClass.new&lt;br /&gt;
           new_obj.method2 &lt;br /&gt;
&lt;br /&gt;
           ## Adding instance method to the instance 'new_obj'&lt;br /&gt;
           new_obj.instance_eval do&lt;br /&gt;
           def method3&lt;br /&gt;
            puts &amp;quot;This is method3&amp;quot;&lt;br /&gt;
           end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           new_obj.method3&lt;br /&gt;
           other_obj = NewClass.method3&lt;br /&gt;
           other_obj.method&lt;br /&gt;
           &lt;br /&gt;
Here, the method 'method2' can be invoked on the class 'NewClass' but not on it's any instance since it is a class method. The method 'method3' can be invoked on the instance 'new_obj' only and not on the instance 'other_obj'. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54556</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54556"/>
		<updated>2011-11-01T16:36:23Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Evolution of Meta-programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54555</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54555"/>
		<updated>2011-11-01T16:34:56Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Uses of Meta-programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54554</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54554"/>
		<updated>2011-11-01T16:34:28Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of a meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming meta-programming].&lt;br /&gt;
We can also define a meta-program as a program which generates code and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingrediant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54461</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54461"/>
		<updated>2011-10-31T19:41:35Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
Note that if a class already has a built-in method with the name same as new method, then Ruby replaces the built-in method with the new one and so the original implementation of built-in method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54460</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54460"/>
		<updated>2011-10-31T19:39:31Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    String.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_reader( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
              String.class_eval &amp;quot;def #{instance_variable};@#{instance_variable};end&amp;quot; &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object of class String. So, we use this class to redefine methods and also to add new methods. For instance, we can add new instance methods of a class by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. We can also use techniques like instance_variables to indicate the instance_variables in the class. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          4.times do&lt;br /&gt;
     	    class A&lt;br /&gt;
              def method1&lt;br /&gt;
                puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class A is evaluated four times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined four times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class A will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class A&lt;br /&gt;
            def method1&lt;br /&gt;
               puts &amp;quot;This is method1&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which returns the array of the square  of the elements in an array. It can be done by defining a square method as follows: &lt;br /&gt;
&lt;br /&gt;
           def square(array)&lt;br /&gt;
              arr_square = []&lt;br /&gt;
              array.each_with_index do |e, i|&lt;br /&gt;
                 arr_square[i] = e*e&lt;br /&gt;
              end&lt;br /&gt;
              return arr_square&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def square&lt;br /&gt;
                 arr_square = []&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    arr_square[i] = e*e&lt;br /&gt;
                 end&lt;br /&gt;
                 return arr_square&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4] &lt;br /&gt;
           puts a.square.to_s                         #  [1, 4, 9, 16]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion == &lt;br /&gt;
So, we can conclude by saying that various techniques and properties like singleton classes, method aliasing, class definitions and modules help in implementing this simple yet powerful feature called meta-programming efficiently in Ruby. Thus we can also say that Ruby has this powerful feature inbuilt within the language and can implement it with all the various techniques as discussed in this page.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54205</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54205"/>
		<updated>2011-10-28T02:45:44Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so the definition of the class MyClass is evaluated three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54204</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54204"/>
		<updated>2011-10-28T00:06:55Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Singleton classes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array (since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54203</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=54203"/>
		<updated>2011-10-28T00:06:24Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Singleton classes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of Array(since Array class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name.&lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1. Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2. Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53153</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53153"/>
		<updated>2011-10-20T19:04:31Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Further reading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1.Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2.Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3.Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53152</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53152"/>
		<updated>2011-10-20T19:04:19Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. [http://en.wikipedia.org/wiki/Ruby_on_Rails Ruby on Rails] is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== Evolution of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1.Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2.Meta Programming in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://rubysource.com/ruby-metaprogramming-part-i/ 3. Ruby Metaprogramming: Part I]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53147</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53147"/>
		<updated>2011-10-20T18:53:36Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Futher reading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 1.Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf 2.Meta Programming in Ruby]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53144</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53144"/>
		<updated>2011-10-20T18:51:45Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Modules */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;[http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby]&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;[http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby]&amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;[http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Futher reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf Meta Programming in Ruby]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53143</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53143"/>
		<updated>2011-10-20T18:51:05Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
5)      Lately, meta programming has many advantages in the field of [http://en.wikipedia.org/wiki/Artificial_intelligence Artificial Intelligence].&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;[http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes]&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;[http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;[http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods]&amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby &amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Futher reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf Meta Programming in Ruby]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53141</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53141"/>
		<updated>2011-10-20T18:48:24Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Modules */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods &amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html Modules in Ruby&amp;lt;/ref&amp;gt; &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby &amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Futher reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf Meta Programming in Ruby]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53140</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53140"/>
		<updated>2011-10-20T18:43:56Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Modules */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods &amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of [http://en.wikipedia.org/wiki/Multiple_inheritance multiple inheritance] in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby &amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Futher reading ==&lt;br /&gt;
[http://www.slideshare.net/bsbodden/ruby-metaprogramming-08 Implementation of Meta programming in Ruby and its application on a framework called Rails]&lt;br /&gt;
&lt;br /&gt;
[http://assets.en.oreilly.com/1/event/12/Metaprogramming%20in%20Ruby%20Presentation%201.pdf Meta Programming in Ruby]&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53131</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53131"/>
		<updated>2011-10-20T18:38:33Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_open_classes.html Open Classes in Ruby]&amp;lt;/ref&amp;gt; helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/ruby_overloading_methods.html Method over-loading in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
             if args.size == 2&lt;br /&gt;
                puts 'Two arguments'&lt;br /&gt;
             else&lt;br /&gt;
                puts 'Three arguments'&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Three arguements &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
    #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
    #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&amp;lt;ref&amp;gt;[http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html Meta programming in Ruby Overview]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&amp;lt;ref&amp;gt;[http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html Singleton classes implementation and its uses in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&amp;lt;ref&amp;gt;[http://courses.ncsu.edu/csc517//common/lectures/notes/lec12.pdf Lecture Notes on Meta programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&amp;lt;ref&amp;gt;[http://www.zenspider.com/Languages/Ruby/QuickRef.html#31 Aliasing representation in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept.&amp;lt;ref&amp;gt;[http://ruby.about.com/od/rubyfeatures/a/aliasing.htm Method aliasing in Ruby]&amp;lt;/ref&amp;gt; Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-module_eval module_eval] method.&amp;lt;ref&amp;gt;http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name &amp;quot;Xyz&amp;quot; in the program’s namespace and make sure it behaves like a normal class as if it is defined using the 'class' keyword.&lt;br /&gt;
&lt;br /&gt;
The class can be instantiated and its attributes can be accessed in the following way.&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-const_get const_get] method and the attribute is set and read using [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_set instance_variable_set] and [http://www.ruby-doc.org/core-1.9.2/Object.html#method-i-instance_variable_get instance_variable_get] methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The [http://www.ruby-doc.org/core-1.9.2/Module.html#method-i-class_eval class_eval] method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods &amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby &amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53124</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53124"/>
		<updated>2011-10-20T18:16:39Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Modules */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called Ruby. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and vice versa. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
          end&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10) &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
Singleton classes are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. Also, we can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the module_eval method of class Object.&amp;lt;ref&amp;gt;http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name “Xyz” in the program’s namespace and make sure it behaves like a normal class as if it is defined using the ‘class’ keyword.&lt;br /&gt;
The class can be instantiated and its attributes can be  accessed in the following way:&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the const_get method of class Object and the attribute is set and read using instance_variable_set and instance_variable_get methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The class_eval method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods &amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself.&amp;lt;ref&amp;gt;http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ Include vs Extend in Ruby &amp;lt;/ref&amp;gt; One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&amp;lt;ref&amp;gt;http://blog.jayfields.com/2006/05/ruby-extend-and-include.html Ruby extend and include &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53122</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53122"/>
		<updated>2011-10-20T18:14:23Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?MetaProgramming Overview of uses of Meta Programming]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language], one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code.&lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called Ruby. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and vice versa. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
          end&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10) &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
Singleton classes are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. Also, we can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the module_eval method of class Object.&amp;lt;ref&amp;gt;http://bathroom.baclayon.com/ruby/dynamic.html#class Dynamically creating classes&amp;lt;/ref&amp;gt; Let us see an example of how the above class can be defined using module_eval method.&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method.&amp;lt;ref&amp;gt;http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/ How to create a class on the fly in Ruby&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name “Xyz” in the program’s namespace and make sure it behaves like a normal class as if it is defined using the ‘class’ keyword.&lt;br /&gt;
The class can be instantiated and its attributes can be  accessed in the following way:&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the const_get method of class Object and the attribute is set and read using instance_variable_set and instance_variable_get methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The class_eval method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&amp;lt;ref&amp;gt;http://www.raulparolari.com/Ruby2/define_method Defining dynamic methods &amp;lt;/ref&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself. One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53118</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53118"/>
		<updated>2011-10-20T18:06:25Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Modules */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called [http://en.wikipedia.org/wiki/Metaprogramming Meta-programming].&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
In C-language, one of the popular examples of meta-programming is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
In C++, meta-programming is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
Prolog, a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called Ruby. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and vice versa. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
          end&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10) &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
Singleton classes are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. Also, we can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the module_eval method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using module_eval method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name “Xyz” in the program’s namespace and make sure it behaves like a normal class as if it is defined using the ‘class’ keyword.&lt;br /&gt;
The class can be instantiated and its attributes can be  accessed in the following way:&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the const_get method of class Object and the attribute is set and read using instance_variable_set and instance_variable_get methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The class_eval method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself. One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end          &lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                          # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
           Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
           Car.left 			        # NoMethodError &lt;br /&gt;
           Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53114</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53114"/>
		<updated>2011-10-20T18:01:01Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called Meta-programming.&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
In C-language, one of the popular examples of meta-programming is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
In C++, meta-programming is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
Prolog, a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called Ruby. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and vice versa. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
          end&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10) &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
Singleton classes are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. Also, we can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the module_eval method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using module_eval method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name “Xyz” in the program’s namespace and make sure it behaves like a normal class as if it is defined using the ‘class’ keyword.&lt;br /&gt;
The class can be instantiated and its attributes can be  accessed in the following way:&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class                                     # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the const_get method of class Object and the attribute is set and read using instance_variable_set and instance_variable_get methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The class_eval method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		                        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		                        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname                                    # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname                                    # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself. One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                         # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
            Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
            Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
            Car.left 			        # NoMethodError &lt;br /&gt;
            Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53113</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53113"/>
		<updated>2011-10-20T17:57:56Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Modules */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called Meta-programming.&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
In C-language, one of the popular examples of meta-programming is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
In C++, meta-programming is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
Prolog, a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called Ruby. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and vice versa. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
          end&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10) &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
Singleton classes are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. Also, we can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the module_eval method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using module_eval method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;		                             # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;		                             # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name “Xyz” in the program’s namespace and make sure it behaves like a normal class as if it is defined using the ‘class’ keyword.&lt;br /&gt;
The class can be instantiated and its attributes can be  accessed in the following way:&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class					# &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the const_get method of class Object and the attribute is set and read using instance_variable_set and instance_variable_get methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The class_eval method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname              # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname              # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself. One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def left&lt;br /&gt;
                 puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
              def self.right&lt;br /&gt;
                 puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
               include Actions&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           Car.new.left                         # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Car.new.right 			# NoMethodError&lt;br /&gt;
           Car.left         			# NoMethodError&lt;br /&gt;
    &lt;br /&gt;
           class Truck&lt;br /&gt;
              extend Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
           Truck.left 			        # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           Truck.right 		        	# NoMethodError&lt;br /&gt;
           Truck.new.left 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
           class Car&lt;br /&gt;
           end&lt;br /&gt;
           car = Car.new&lt;br /&gt;
           car.extend Actions&lt;br /&gt;
           car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
           car2 = Car.new&lt;br /&gt;
           car2.left 			        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&lt;br /&gt;
&lt;br /&gt;
           module Actions&lt;br /&gt;
              def self.included(base)&lt;br /&gt;
                 base.extend(ClassMethods)&lt;br /&gt;
              end&lt;br /&gt;
              def left&lt;br /&gt;
                 puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           module ClassMethods&lt;br /&gt;
              def right&lt;br /&gt;
                 puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           &lt;br /&gt;
           class Car&lt;br /&gt;
              include Actions&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
            Car.right 			        # &amp;quot;class method - right&amp;quot;&lt;br /&gt;
            Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
            Car.left 			        # NoMethodError &lt;br /&gt;
            Car.new.right 		        # NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53110</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53110"/>
		<updated>2011-10-20T17:51:02Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called Meta-programming.&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
In C-language, one of the popular examples of meta-programming is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
In C++, meta-programming is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
Prolog, a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called Ruby. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and vice versa. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
          end&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10) &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
&lt;br /&gt;
=== Singleton classes ===&lt;br /&gt;
Singleton classes are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. Also, we can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the module_eval method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using module_eval method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;		                             # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;		                             # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name “Xyz” in the program’s namespace and make sure it behaves like a normal class as if it is defined using the ‘class’ keyword.&lt;br /&gt;
The class can be instantiated and its attributes can be  accessed in the following way:&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class					# &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the const_get method of class Object and the attribute is set and read using instance_variable_set and instance_variable_get methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The class_eval method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		        #  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname              # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname              # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself. One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
module Actions&lt;br /&gt;
		def left&lt;br /&gt;
			puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
def self.right&lt;br /&gt;
		puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
class Car&lt;br /&gt;
	include Actions&lt;br /&gt;
end&lt;br /&gt;
Car.new.left 			# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
Car.new.right 			# NoMethodError&lt;br /&gt;
Car.left         			# NoMethodError&lt;br /&gt;
class Truck&lt;br /&gt;
	extend Actions&lt;br /&gt;
end&lt;br /&gt;
Truck.left 			 # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
Truck.right 			# NoMethodError&lt;br /&gt;
Truck.new.left 		# NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
class Car&lt;br /&gt;
end&lt;br /&gt;
car = Car.new&lt;br /&gt;
car.extend Actions&lt;br /&gt;
car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
car2 = Car.new&lt;br /&gt;
car2.left 			# NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&lt;br /&gt;
&lt;br /&gt;
module Actions&lt;br /&gt;
 	def self.included(base)&lt;br /&gt;
    		base.extend(ClassMethods)&lt;br /&gt;
	end&lt;br /&gt;
		def left&lt;br /&gt;
			puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
	end&lt;br /&gt;
      	module ClassMethods&lt;br /&gt;
		def right&lt;br /&gt;
			puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
           end&lt;br /&gt;
class Car&lt;br /&gt;
  	include Actions&lt;br /&gt;
end&lt;br /&gt;
Car.right 			# &amp;quot;class method - right&amp;quot;&lt;br /&gt;
Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
Car.left 			# NoMethodError &lt;br /&gt;
Car.new.right 			# NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53107</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53107"/>
		<updated>2011-10-20T17:49:48Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called Meta-programming.&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
In C-language, one of the popular examples of meta-programming is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
In C++, meta-programming is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
Prolog, a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called Ruby. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and vice versa. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
          end&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10) &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
&lt;br /&gt;
Singleton classes are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. Also, we can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the module_eval method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using module_eval method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;		                             # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;		                             # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name “Xyz” in the program’s namespace and make sure it behaves like a normal class as if it is defined using the ‘class’ keyword.&lt;br /&gt;
The class can be instantiated and its attributes can be  accessed in the following way:&lt;br /&gt;
&lt;br /&gt;
            dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
            inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
            puts inst.class					    # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
            inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
            puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the const_get method of class Object and the attribute is set and read using instance_variable_set and instance_variable_get methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The class_eval method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
            attrs = [attr_name]&lt;br /&gt;
            dynamic_class.class_eval do&lt;br /&gt;
      	       attr_accessor *attrs&lt;br /&gt;
            end&lt;br /&gt;
            inst.name = &amp;quot;John&amp;quot;		#  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
            puts inst.name 		        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&lt;br /&gt;
        &lt;br /&gt;
            class Employee&lt;br /&gt;
               ATTRS = [:fname, :lname]&lt;br /&gt;
  	       def initialize *args  &lt;br /&gt;
                  @data = Hash.new&lt;br /&gt;
                  ATTRS.each_with_index do |attr, i|&lt;br /&gt;
                     @data[attr] = args[i]&lt;br /&gt;
      		  end&lt;br /&gt;
  	       end&lt;br /&gt;
               ATTRS.each do |attr|&lt;br /&gt;
                  define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
                     @data[attr.to_sym]&lt;br /&gt;
                  end	&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
            puts e.get_fname              # &amp;quot;John&amp;quot;&lt;br /&gt;
            puts e.get_lname              # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
            eval %{def get_#{attr}&lt;br /&gt;
               @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
            end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself. One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
module Actions&lt;br /&gt;
		def left&lt;br /&gt;
			puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
def self.right&lt;br /&gt;
		puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
class Car&lt;br /&gt;
	include Actions&lt;br /&gt;
end&lt;br /&gt;
Car.new.left 			# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
Car.new.right 			# NoMethodError&lt;br /&gt;
Car.left         			# NoMethodError&lt;br /&gt;
class Truck&lt;br /&gt;
	extend Actions&lt;br /&gt;
end&lt;br /&gt;
Truck.left 			 # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
Truck.right 			# NoMethodError&lt;br /&gt;
Truck.new.left 		# NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
class Car&lt;br /&gt;
end&lt;br /&gt;
car = Car.new&lt;br /&gt;
car.extend Actions&lt;br /&gt;
car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
car2 = Car.new&lt;br /&gt;
car2.left 			# NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&lt;br /&gt;
&lt;br /&gt;
module Actions&lt;br /&gt;
 	def self.included(base)&lt;br /&gt;
    		base.extend(ClassMethods)&lt;br /&gt;
	end&lt;br /&gt;
		def left&lt;br /&gt;
			puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
	end&lt;br /&gt;
      	module ClassMethods&lt;br /&gt;
		def right&lt;br /&gt;
			puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
           end&lt;br /&gt;
class Car&lt;br /&gt;
  	include Actions&lt;br /&gt;
end&lt;br /&gt;
Car.right 			# &amp;quot;class method - right&amp;quot;&lt;br /&gt;
Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
Car.left 			# NoMethodError &lt;br /&gt;
Car.new.right 			# NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53102</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53102"/>
		<updated>2011-10-20T17:45:54Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called Meta-programming.&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
In C-language, one of the popular examples of meta-programming is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
In C++, meta-programming is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
Prolog, a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called Ruby. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and vice versa. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
          end&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10) &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
&lt;br /&gt;
Singleton classes are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&lt;br /&gt;
&lt;br /&gt;
        alias        :new  :old&lt;br /&gt;
        alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
     class Array&lt;br /&gt;
      def product&lt;br /&gt;
          inject {|a, x| a*x }&lt;br /&gt;
      end&lt;br /&gt;
      alias  :newproduct :product&lt;br /&gt;
     end&lt;br /&gt;
     a = Array.new([1, 2, 3, 4])&lt;br /&gt;
     a.newproduct   #=&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. Also, we can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
          class A&lt;br /&gt;
            def method1&lt;br /&gt;
              puts ”This is the main method”&lt;br /&gt;
            end&lt;br /&gt;
            alias :method2 :method1&lt;br /&gt;
            def method1&lt;br /&gt;
               puts “This is not main method&amp;quot;&lt;br /&gt;
               method2&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
          a = A.new()&lt;br /&gt;
          a.method1&lt;br /&gt;
          =&amp;gt; This is not main method&lt;br /&gt;
          =&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
         class MyClass&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	    end&lt;br /&gt;
            def one&lt;br /&gt;
               puts &amp;quot;one&amp;quot;&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
              def one     &lt;br /&gt;
                 puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
           def replace(array, from, to)&lt;br /&gt;
              array.each_with_index do |e i|&lt;br /&gt;
                 array[i] = to if e == from&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
&lt;br /&gt;
           class Array&lt;br /&gt;
              def replace(from,to)&lt;br /&gt;
                 self.each_with_index do |e, i|&lt;br /&gt;
                    self[i] = to if e == from&lt;br /&gt;
                 end&lt;br /&gt;
              end&lt;br /&gt;
           end&lt;br /&gt;
           a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
           a.replace(2,0) &lt;br /&gt;
           puts a.to_s                         #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
               attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the module_eval method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using module_eval method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;		                             # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
            Object.module_eval(str)                                  # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method:&lt;br /&gt;
&lt;br /&gt;
            class_name = &amp;quot;Xyz&amp;quot;                                       # assume this is inputted by the user&lt;br /&gt;
            attr_name = &amp;quot;name&amp;quot;		                             # assume this is inputted by the user&lt;br /&gt;
            dynamic_class = Object.const_set(class_name, Class.new)  # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name “Xyz” in the program’s namespace and make sure it behaves like a normal class as if it is defined using the ‘class’ keyword.&lt;br /&gt;
The class can be instantiated and its attributes can be  accessed in the following way:&lt;br /&gt;
&lt;br /&gt;
        dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
        inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
        puts inst.class					    # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
        inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
        puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
        inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
        puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the const_get method of class Object and the attribute is set and read using instance_variable_set and instance_variable_get methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The class_eval method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
        attrs = [attr_name]&lt;br /&gt;
        dynamic_class.class_eval do&lt;br /&gt;
      	    attr_accessor *attrs&lt;br /&gt;
        end&lt;br /&gt;
        inst.name = &amp;quot;John&amp;quot;		#  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
        puts inst.name 		        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&lt;br /&gt;
        &lt;br /&gt;
        class Employee&lt;br /&gt;
            ATTRS = [:fname, :lname]&lt;br /&gt;
  	    def initialize *args  &lt;br /&gt;
      		@data = Hash.new&lt;br /&gt;
      		ATTRS.each_with_index do |attr, i|&lt;br /&gt;
         		@data[attr] = args[i]&lt;br /&gt;
      		end&lt;br /&gt;
  	    end&lt;br /&gt;
            ATTRS.each do |attr|&lt;br /&gt;
   		define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
         			@data[attr.to_sym]&lt;br /&gt;
    		end	&lt;br /&gt;
  	     end&lt;br /&gt;
         end&lt;br /&gt;
         e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
         puts e.get_fname              # &amp;quot;John&amp;quot;&lt;br /&gt;
         puts e.get_lname              # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
      eval %{def get_#{attr}&lt;br /&gt;
         @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
      end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself. One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
module Actions&lt;br /&gt;
		def left&lt;br /&gt;
			puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
def self.right&lt;br /&gt;
		puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
class Car&lt;br /&gt;
	include Actions&lt;br /&gt;
end&lt;br /&gt;
Car.new.left 			# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
Car.new.right 			# NoMethodError&lt;br /&gt;
Car.left         			# NoMethodError&lt;br /&gt;
class Truck&lt;br /&gt;
	extend Actions&lt;br /&gt;
end&lt;br /&gt;
Truck.left 			 # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
Truck.right 			# NoMethodError&lt;br /&gt;
Truck.new.left 		# NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
class Car&lt;br /&gt;
end&lt;br /&gt;
car = Car.new&lt;br /&gt;
car.extend Actions&lt;br /&gt;
car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
car2 = Car.new&lt;br /&gt;
car2.left 			# NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&lt;br /&gt;
&lt;br /&gt;
module Actions&lt;br /&gt;
 	def self.included(base)&lt;br /&gt;
    		base.extend(ClassMethods)&lt;br /&gt;
	end&lt;br /&gt;
		def left&lt;br /&gt;
			puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
	end&lt;br /&gt;
      	module ClassMethods&lt;br /&gt;
		def right&lt;br /&gt;
			puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
           end&lt;br /&gt;
class Car&lt;br /&gt;
  	include Actions&lt;br /&gt;
end&lt;br /&gt;
Car.right 			# &amp;quot;class method - right&amp;quot;&lt;br /&gt;
Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
Car.left 			# NoMethodError &lt;br /&gt;
Car.new.right 			# NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53094</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4g as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4g_as&amp;diff=53094"/>
		<updated>2011-10-20T17:38:24Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In this page, the concept of Meta-programming in Ruby is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of Meta-program in general i.e., its evolution and implementation in various languages is discussed. We then, discuss about the implementation of the concept of meta-programming in a dynamic and object-oriented programming language called Ruby.&lt;br /&gt;
&lt;br /&gt;
== Definitions ==&lt;br /&gt;
&lt;br /&gt;
A program that manipulates its code or other program’s code as its data is called a meta-program. An established example of meta-program is a compiler. The act of writing these meta-programs, that write or manipulate other programs or themselves as data is called Meta-programming.&lt;br /&gt;
We can also define meta-program as code generating program and writing such programs is called meta-programming.&lt;br /&gt;
&lt;br /&gt;
This allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
1)	The major use of meta-programming is that it pre-generates the code at run-time. For example if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup of runtime.&lt;br /&gt;
&lt;br /&gt;
2)	It is the key ingradiant for Domain Specific Languages. That is we use meta-programming to encapsulate domain-specific knowledge.&lt;br /&gt;
&lt;br /&gt;
3)	Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code. Also the maintenance becomes easy.&lt;br /&gt;
&lt;br /&gt;
4)	Also, we can use meta-programming for building frameworks and thus perform web application development. Ruby on Rails is one such example. Ruby’s meta-programming feature is the key feature for developing web application in Rails.&lt;br /&gt;
&lt;br /&gt;
== History of Meta-programming ==&lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time.&lt;br /&gt;
 &lt;br /&gt;
In C-language, one of the popular examples of meta-programming is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. Instead of doing the laborious work of generating a parser in C, one can use Yacc to generate the repetitive parts of the program. Then, one can add only the code necessary to operate on the parsed entities.&lt;br /&gt;
&lt;br /&gt;
In C++, meta-programming is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written inbetween question marks. Usually this code is quite complicated and consists of a template and some instructions on how to fill the code. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code.&lt;br /&gt;
Prolog, a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
== Meta programming in Ruby == &lt;br /&gt;
In this column, we will discuss about the implementation of meta-programming in a programming language called Ruby. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and vice versa. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime. One of the major applications of Ruby is in Rails. Rails is a framework, which can be used for web applications development. The feature of meta-programming in Ruby is the key in building this rails framework. &lt;br /&gt;
&lt;br /&gt;
Open class property of Ruby helps it to enhance the implement of the concept of meta-programming efficiently. In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example:&lt;br /&gt;
&lt;br /&gt;
    a = [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Here ‘a’ is an array and if we want to find the product of all the elements of the array, we need to open the Array class and add the method to calculate the product of the array elements.&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product&lt;br /&gt;
        inject{|a,x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
We can now call method product for the array.&lt;br /&gt;
        &lt;br /&gt;
        a.product&lt;br /&gt;
        =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Generally we add the methods to the classes rather than the class objects, because adding to class objects will make the methods visible and thereby affecting the encapsulation. Sometimes adding a method can override already existing method. So, it is sometimes better to create a subclass to the existing class and add the method to the subclass.&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
 &lt;br /&gt;
    # The Rectangle constructor accepts arguments in either&lt;br /&gt;
    # of the following forms:&lt;br /&gt;
    class Rectangle&lt;br /&gt;
       def initialize(*args)&lt;br /&gt;
          if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
             puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
          else&lt;br /&gt;
             puts 'Correct number of arguments passed!!!'&lt;br /&gt;
          end&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    Rectangle.new([10, 23], 4, 10) &lt;br /&gt;
    Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
&lt;br /&gt;
Singleton classes are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class. So firstly, let us understand what a singleton class means and then we will discuss about how it enhances the implementation of meta-programming in Ruby.&lt;br /&gt;
&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class. So, whenever the additional method defined for the object is called, the singleton class is searched first and then the actual class is searched (for the implementation).  Let us look at the following example to understand this. Consider an array object a defined as follows:&lt;br /&gt;
&lt;br /&gt;
          a= [1, 2, 3, 4]&lt;br /&gt;
&lt;br /&gt;
Now, if we want to add a new method to this object which will find out the product of all the elements in the array, we can do it as follows:&lt;br /&gt;
&lt;br /&gt;
     class &amp;lt;&amp;lt; a&lt;br /&gt;
       def prod&lt;br /&gt;
         inject{|a, x| a*x}&lt;br /&gt;
       end&lt;br /&gt;
     end&lt;br /&gt;
&lt;br /&gt;
Now we can call,&lt;br /&gt;
&lt;br /&gt;
         a.prod&lt;br /&gt;
         =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
Here, when the method prod is called by object a, a singleton class is created between the object and its actual class. This class is hidden and has no name. Also, we cannot instantiate a new object from this hidden anonymous class.&lt;br /&gt;
&lt;br /&gt;
Now, let us discuss about another aspect of singleton classes. As we know all the objects can have a singleton class. Also, any class is actually an object of itself and also of the class Class. That is, the class Array is an object of itself and also of class Class. Suppose that, we define a method called prod just as above for this class Array, that method will actually be executed in the scope of the Array instance of the class Class (since Array is an object of Class class). The following is an example illustrating this:&lt;br /&gt;
&lt;br /&gt;
        a = [1, 2, 3, 4]&lt;br /&gt;
        class Array&lt;br /&gt;
        class &amp;lt;&amp;lt; self&lt;br /&gt;
           def prod&lt;br /&gt;
               inject {|a, x| a*x}&lt;br /&gt;
           end&lt;br /&gt;
        end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
Here, the method prod will be defined in the singleton class of String (since String class is considered as an object of Class class). Here we are using the variable self because it always refers to the current object (which is by default the receiver of the method call). So here, self refers to the current object of the class Class i.e., Array.&lt;br /&gt;
&lt;br /&gt;
Now let us look at the use of these singleton classes. The addition of the methods to instances and classes (as discussed above) are some of the uses of singleton classes. Various tricks/methods of Ruby like class_eval, module_eval, instance_variables etc., when invoked on singleton classes will be simple yet powerful in terms of efficiency of implementation of meta-programming, rather than invoking those tricks/methods on self. The following example in which, some of the above mentioned tricks/methods are invoked on a singleton class of an object will illustrate this advantage:&lt;br /&gt;
&lt;br /&gt;
    Object.class_eval do&lt;br /&gt;
      class &amp;lt;&amp;lt; self&lt;br /&gt;
        def attribute_accessor( *instance_variables )&lt;br /&gt;
          instance_variables.each do |instance_variable|&lt;br /&gt;
          class_eval %Q?&lt;br /&gt;
   	    def #{instance_variable}&lt;br /&gt;
               @#{instance_variable}&lt;br /&gt;
            end&lt;br /&gt;
            def #{instance_variable}=( new_value )&lt;br /&gt;
               @#{instance_variable} = new_value&lt;br /&gt;
            end&lt;br /&gt;
          ? &lt;br /&gt;
  	  end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
Here, we can see that a singleton class is being created for any object. So, we use this class to redefine methods and also to add new methods. For instance, we can add new class methods by using the class_eval method (trick) without actually typing the class name explicitly. Also, we can get to know the name of the class the object belongs to by calling the method instance_variable. In this manner we can use all these methods in singleton class and modify methods and variables without actually typing the class name. &lt;br /&gt;
&lt;br /&gt;
=== Method aliasing ===&lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable.&lt;br /&gt;
&lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and there by change the behavior of an object or a class. Also, we can use aliasing for more expressive options to the programmer using the class. That is, we can provide a second name to a method or variable which can be used outside the class too. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords:&lt;br /&gt;
&lt;br /&gt;
	alias        :new  :old&lt;br /&gt;
	alias_method :new, :old&lt;br /&gt;
&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Generally, we use labels to refer to the methods and the variables for which aliasing is being done.&lt;br /&gt;
Let us look at an example that illustrates this technique. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    class Array&lt;br /&gt;
       def product	&lt;br /&gt;
         inject {|a, x| a*x }&lt;br /&gt;
       end&lt;br /&gt;
    alias  :newproduct :product&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newproduct&lt;br /&gt;
    =&amp;gt; 24&lt;br /&gt;
&lt;br /&gt;
In this example, we are defining a new method called product and then aliasing that method with a new name called newproduct in the class Array. Now we can call this method with its alias name as above and still the method will be invoked. This is how method aliasing can be implementing. Also, we can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this:&lt;br /&gt;
&lt;br /&gt;
         class A&lt;br /&gt;
	    def method1&lt;br /&gt;
	      puts ”This is the main method”&lt;br /&gt;
	   end&lt;br /&gt;
	   alias :method2 :method1&lt;br /&gt;
	 &lt;br /&gt;
   	   def method1&lt;br /&gt;
	       puts “This is not main method”&lt;br /&gt;
	       method2&lt;br /&gt;
               end&lt;br /&gt;
	 end	&lt;br /&gt;
	a = A.new()&lt;br /&gt;
	a.method1&lt;br /&gt;
	=&amp;gt; This is not main method&lt;br /&gt;
	=&amp;gt; This is main method	&lt;br /&gt;
&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming. Also, using method aliasing enables Ruby to implement Aspect Oriented Programming and its libraries.&lt;br /&gt;
&lt;br /&gt;
=== Class Definitions === &lt;br /&gt;
In statically typed languages, the classes are defined at compile time and used by the program at runtime. But dynamically typed languages do not consider this distinction. In Ruby, the class definitions are expressions and they are evaluated at run time just like any other code. So, the classes and its attributes and even methods can be defined at runtime. &lt;br /&gt;
Look at the following example:&lt;br /&gt;
&lt;br /&gt;
          3.times do&lt;br /&gt;
     	    class MyClass&lt;br /&gt;
              def one&lt;br /&gt;
                puts &amp;quot;one&amp;quot;&lt;br /&gt;
              end&lt;br /&gt;
            end&lt;br /&gt;
          end&lt;br /&gt;
&lt;br /&gt;
This code is evaluated at runtime and so it defines the class MyClass three times. You might think that it is invalid to define the same class several times. But remember, when Ruby comes across the definition of a class which already have been defined earlier, it just opens the class definition and appends the code in the new definition to the code in the old definition. So, the definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
 	class MyClass&lt;br /&gt;
          def one&lt;br /&gt;
            puts &amp;quot;one&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
          def one&lt;br /&gt;
            puts &amp;quot;one&amp;quot;&lt;br /&gt;
       	  end&lt;br /&gt;
          def one&lt;br /&gt;
            puts &amp;quot;one&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&lt;br /&gt;
But as you can see the same method is defined three times. Ruby replaces the old definition of a method with the new one every time it comes across a new definition of the same method. So the final definition of class MyClass will look like as follows:&lt;br /&gt;
&lt;br /&gt;
           class MyClass&lt;br /&gt;
        	  def one&lt;br /&gt;
                     puts &amp;quot;one&amp;quot;&lt;br /&gt;
        	  end&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to add methods to an existing class at runtime. Suppose we want to define a method which replaces the elements with a certain value in an array with another value. It can be done by defining a replace method as follows: &lt;br /&gt;
&lt;br /&gt;
            def replace(array, from, to)&lt;br /&gt;
	      array.each_with_index do |e i|&lt;br /&gt;
		array[i] = to if e == from&lt;br /&gt;
	      end&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
But this is not an object-oriented approach as this method has nothing to do with the class in which the replace method is defined. The replace method is in fact dealing with the elements of an array. So, the object-oriented approach will be to define the replace method in the class Array. But the class Array is already defined in Ruby, so we can add the replace method by simply defining the class Array again with the replace method definition in it as follows:&lt;br /&gt;
            class Array&lt;br /&gt;
               def replace(from,to)&lt;br /&gt;
                  self.each_with_index do |e, i|&lt;br /&gt;
	          self[i] = to if e == from&lt;br /&gt;
	          end&lt;br /&gt;
               end&lt;br /&gt;
            end&lt;br /&gt;
            a = [1,2,3,4,5,6,2,3,4,5,2,3,2]&lt;br /&gt;
            a.replace(2,0) &lt;br /&gt;
            puts a.to_s          #  [1, 0, 3, 4, 5, 6, 0, 3, 4, 5, 0, 3, 0]&lt;br /&gt;
&lt;br /&gt;
But there is a problem in defining the replace method for the class Array. The class Array already has a built-in replace method. So, when we define the new replace method, Ruby replaces the built-in replace method with the new one and so the original implementation of replace method is lost.  &lt;br /&gt;
&lt;br /&gt;
Now we will look at how a new class and it attributes are defined at runtime. This is useful when the programmer doesn't know what will be the names of the class and its attributes until runtime.&lt;br /&gt;
In Ruby, a class and its attributes are defined statically as follows:&lt;br /&gt;
&lt;br /&gt;
            class Xyz&lt;br /&gt;
       		attr_accessor :name&lt;br /&gt;
            end&lt;br /&gt;
&lt;br /&gt;
In Ruby, one way to define a class and its attributes at runtime is to use the module_eval method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using module_eval method:&lt;br /&gt;
&lt;br /&gt;
class_name = &amp;quot;Xyz&amp;quot;		                                    # assume this is inputted by the user&lt;br /&gt;
attr_name = &amp;quot;name&amp;quot;                                                    # assume this is inputted by the user&lt;br /&gt;
str = (&amp;quot;class #{class_name}; #{attr_name}; end&amp;quot;)&lt;br /&gt;
Object.module_eval(str)                                             # create the class&lt;br /&gt;
&lt;br /&gt;
In the above code, the class_name and attr_name variables contain the class name and the attribute name which are provided by the user at runtime. The module_eval evaluates the string formed for defining the class and  creates the class using the value contained by class_name variable and an attribute using the value contained by attr_name variable. It  adds the class name as a constant in the program's namespace.&lt;br /&gt;
An another way to define a class and its attributes at runtime  is to use const_set method of class Object.&lt;br /&gt;
Let us see an example of how the above class can be defined using const_set method:&lt;br /&gt;
&lt;br /&gt;
class_name = &amp;quot;Xyz&amp;quot;                     # assume this is inputted by the user&lt;br /&gt;
attr_name = &amp;quot;name&amp;quot;		    # assume this is inputted by the user&lt;br /&gt;
dynamic_class = Object.const_set(class_name, Class.new)     # create the class&lt;br /&gt;
&lt;br /&gt;
Here, the const_set method adds the name “Xyz” in the program’s namespace and make sure it behaves like a normal class as if it is defined using the ‘class’ keyword.&lt;br /&gt;
The class can be instantiated and its attributes can be  accessed in the following way:&lt;br /&gt;
&lt;br /&gt;
        dynamic_class = Object.const_get(class_name)        # get the class&lt;br /&gt;
        inst = dynamic_class.new                            # instantiate the class&lt;br /&gt;
        puts inst.class					    # &amp;quot;Xyz&amp;quot;&lt;br /&gt;
        inst.instance_variable_set(&amp;quot;@&amp;quot;+attr_name, &amp;quot;John&amp;quot;)   # set @name to &amp;quot;John&amp;quot;&lt;br /&gt;
        puts inst.instance_variable_get(&amp;quot;@&amp;quot;+attr_name)      # &amp;quot;John&amp;quot;  &lt;br /&gt;
        inst.name = &amp;quot;John&amp;quot;                                  # error	&lt;br /&gt;
        puts inst.name                                      # error&lt;br /&gt;
&lt;br /&gt;
The class is instantiated using new method but first the class is retrieved from progam's namespace using the const_get method of class Object and the attribute is set and read using instance_variable_set and instance_variable_get methods. These methods require to have the sing '@' before the attribute name unlike the attribute accessors which use symbol.&lt;br /&gt;
If the attribute 'name' is directly accessed, it will give an error as the attribute accessor methods are not defined for the attribute 'name'.&lt;br /&gt;
&lt;br /&gt;
But, the attribute accessors can be explicitly defined for the attributes using the class_eval method. The class_eval method executes the code between the 'do' and 'end' as if it is written in the static class definition. The class_eval method can also be used to define methods at runtime.&lt;br /&gt;
&lt;br /&gt;
        attrs = [attr_name]&lt;br /&gt;
        dynamic_class.class_eval do&lt;br /&gt;
      	    attr_accessor *attrs&lt;br /&gt;
        end&lt;br /&gt;
        inst.name = &amp;quot;John&amp;quot;		#  set name to &amp;quot;John&amp;quot;&lt;br /&gt;
        puts inst.name 		        # &amp;quot;John&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The attrs is an array which contains all the attributes of the class. The method class_eval executes the line 'attr_accessor *attrs' as if it is defined in the class definition. This causes to define accessor methods for each of the attribute contained in the attrs array. So, the attribute 'name' can be accessed directly.&lt;br /&gt;
&lt;br /&gt;
Now we will look at how to define new methods for a class at runtime. In Ruby, the methods can be generated dynamically using define_method or using def inside of an eval. &lt;br /&gt;
&lt;br /&gt;
The define_method is a private class method and so it must be invoked from within the class context. Its parameters are the method name which can be either a string, a symbol or a variable and the block which becomes the method body.&lt;br /&gt;
        &lt;br /&gt;
        class Employee&lt;br /&gt;
            ATTRS = [:fname, :lname]&lt;br /&gt;
  	    def initialize *args  &lt;br /&gt;
      		@data = Hash.new&lt;br /&gt;
      		ATTRS.each_with_index do |attr, i|&lt;br /&gt;
         		@data[attr] = args[i]&lt;br /&gt;
      		end&lt;br /&gt;
  	    end&lt;br /&gt;
            ATTRS.each do |attr|&lt;br /&gt;
   		define_method &amp;quot;get_#{attr}&amp;quot;  do&lt;br /&gt;
         			@data[attr.to_sym]&lt;br /&gt;
    		end	&lt;br /&gt;
  	     end&lt;br /&gt;
         end&lt;br /&gt;
         e = Employee.new(&amp;quot;John&amp;quot;, &amp;quot;Smith&amp;quot;)&lt;br /&gt;
         puts e.get_fname              # &amp;quot;John&amp;quot;&lt;br /&gt;
         puts e.get_lname              # &amp;quot;Smith&amp;quot;&lt;br /&gt;
&lt;br /&gt;
This could have been done using def keyword also. But there are two important benefits using define_method. First, we can define the method name dynamically. Second one is that the define_method accepts a block as one parameter which is in fact a closure in Ruby. &lt;br /&gt;
The another way to define method dynamically is using def inside an eval. &lt;br /&gt;
&lt;br /&gt;
      eval %{def get_#{attr}&lt;br /&gt;
         @data[&amp;quot;#{attr}&amp;quot;.to_sym]&lt;br /&gt;
      end}&lt;br /&gt;
&lt;br /&gt;
=== Modules ===&lt;br /&gt;
Modules are a way of grouping together methods, constants, classes and other modules in Ruby. &lt;br /&gt;
They are defined using the keyword module. The modules cannot be instantiated nor they can be sub classed. But the modules can be added to the other classes so that the classes can make use of the functionality defined in the modules. &lt;br /&gt;
There are particularly two uses of modules - &lt;br /&gt;
&lt;br /&gt;
They act as namespace and prevent the name clashes that are generally caused by same method names or variable names in different classes.&lt;br /&gt;
The other use is that they share the functionality between classes. A module can be mixed in a class so that functionality defined in that module becomes available to the class at runtime. Modules serve the purpose of multiple inheritance in Ruby indirectly as multiple modules can be mixed in a class. &lt;br /&gt;
&lt;br /&gt;
Either 'include' or 'extend' can be used to mix in a module’s functionality into a class, 'include' is used to add the module’s methods to the instance of a class, while 'extend' is used to add the module's methods to the class itself. One thing it should be noted that only the instance methods of the module are added to the class, no matter either 'include' or 'extend' is used. &lt;br /&gt;
&lt;br /&gt;
module Actions&lt;br /&gt;
		def left&lt;br /&gt;
			puts '&amp;quot;Move to left&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
def self.right&lt;br /&gt;
		puts &amp;quot;Move to right&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
class Car&lt;br /&gt;
	include Actions&lt;br /&gt;
end&lt;br /&gt;
Car.new.left 			# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
Car.new.right 			# NoMethodError&lt;br /&gt;
Car.left         			# NoMethodError&lt;br /&gt;
class Truck&lt;br /&gt;
	extend Actions&lt;br /&gt;
end&lt;br /&gt;
Truck.left 			 # &amp;quot;Move to left&amp;quot;&lt;br /&gt;
Truck.right 			# NoMethodError&lt;br /&gt;
Truck.new.left 		# NoMethodError&lt;br /&gt;
&lt;br /&gt;
The module's methods can added to a particular instance of  the class also.&lt;br /&gt;
&lt;br /&gt;
class Car&lt;br /&gt;
end&lt;br /&gt;
car = Car.new&lt;br /&gt;
car.extend Actions&lt;br /&gt;
car.left				# &amp;quot;Move to left&amp;quot;&lt;br /&gt;
car2 = Car.new&lt;br /&gt;
car2.left 			# NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the methods of module 'Actions' are added to the instance 'car' but they are not added to the instance 'car2' as only instance 'car' extends the module 'Actions'.&lt;br /&gt;
&lt;br /&gt;
If you want to add the class methods of a module to a class, then it can be done by making use of Module#included method.&lt;br /&gt;
&lt;br /&gt;
module Actions&lt;br /&gt;
 	def self.included(base)&lt;br /&gt;
    		base.extend(ClassMethods)&lt;br /&gt;
	end&lt;br /&gt;
		def left&lt;br /&gt;
			puts &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
	end&lt;br /&gt;
      	module ClassMethods&lt;br /&gt;
		def right&lt;br /&gt;
			puts &amp;quot;class method - right&amp;quot;&lt;br /&gt;
		end&lt;br /&gt;
           end&lt;br /&gt;
class Car&lt;br /&gt;
  	include Actions&lt;br /&gt;
end&lt;br /&gt;
Car.right 			# &amp;quot;class method - right&amp;quot;&lt;br /&gt;
Car.new.left 			# &amp;quot;instance method - left&amp;quot;&lt;br /&gt;
Car.left 			# NoMethodError &lt;br /&gt;
Car.new.right 			# NoMethodError&lt;br /&gt;
&lt;br /&gt;
In the above example, the hook of include is used to modify the class that is including the module. The class is modified to extend the methods of Actions::ClassMethods module. As a result the class Car has access to both the class as well as instance methods.&lt;br /&gt;
&lt;br /&gt;
So, in this manner various techniques and properties of Ruby like singleton classes, method aliasing, class definitions and modules help in implementing meta-programming feature efficiently.&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52038</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52038"/>
		<updated>2011-10-15T16:37:53Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. &amp;lt;ref&amp;gt;http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].&amp;lt;ref&amp;gt;http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8 Stack and Heap memory&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&amp;lt;ref&amp;gt;http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.&amp;lt;ref&amp;gt;http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm Primitives in C#&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. &amp;lt;ref&amp;gt;http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Classes in Ruby&amp;lt;/ref&amp;gt; &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. &amp;lt;ref&amp;gt;http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler. Dealing with primitive objects is easier at times. In brief, the primitive objects help to increase the productivity of the programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52037</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52037"/>
		<updated>2011-10-15T16:20:02Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. &amp;lt;ref&amp;gt;http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].&amp;lt;ref&amp;gt;http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8 Stack and Heap memory&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&amp;lt;ref&amp;gt;http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.&amp;lt;ref&amp;gt;http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm Primitives in C#&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. &amp;lt;ref&amp;gt;http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Classes in Ruby&amp;lt;/ref&amp;gt; &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. &amp;lt;ref&amp;gt;http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52036</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52036"/>
		<updated>2011-10-15T16:18:50Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Advantages of primitives */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. &amp;lt;ref&amp;gt;http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].&amp;lt;ref&amp;gt;http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8 Stack and Heap memory&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&amp;lt;ref&amp;gt;http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.&amp;lt;ref&amp;gt;http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm Primitives in C#&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. &amp;lt;ref&amp;gt;http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html&amp;lt;/ref&amp;gt; &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. &amp;lt;ref&amp;gt;http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52035</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52035"/>
		<updated>2011-10-15T16:18:14Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. &amp;lt;ref&amp;gt;http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].&amp;lt;ref&amp;gt;http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8 Stack and Heap memory&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&amp;lt;ref&amp;gt;http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.&amp;lt;ref&amp;gt;http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm Primitives in C#&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. &amp;lt;ref&amp;gt;http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html&amp;lt;/ref&amp;gt; &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. &amp;lt;ref&amp;gt;http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&amp;lt;ref&amp;gt;http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52034</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52034"/>
		<updated>2011-10-15T16:15:38Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. &amp;lt;ref&amp;gt;http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].&amp;lt;ref&amp;gt;http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&amp;lt;ref&amp;gt;http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.&amp;lt;ref&amp;gt;http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm Primitives in C#&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. &amp;lt;ref&amp;gt;http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html&amp;lt;/ref&amp;gt; &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. Here are some:&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&amp;lt;ref&amp;gt;http://www.research.ibm.com/people/a/alpert/ptch/ptch.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52033</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52033"/>
		<updated>2011-10-15T16:10:15Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. &amp;lt;ref&amp;gt;http://www.cafeaulait.org/course/week2/02.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].&amp;lt;ref&amp;gt;http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&amp;lt;ref&amp;gt;http://leepoint.net/notes-java/data/expressions/22compareobjects.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.&amp;lt;ref&amp;gt;http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;[http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. &amp;lt;ref&amp;gt;http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html&amp;lt;/ref&amp;gt; &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. Here are some:&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&amp;lt;ref&amp;gt;http://www.research.ibm.com/people/a/alpert/ptch/ptch.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52032</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52032"/>
		<updated>2011-10-15T16:08:56Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. &amp;lt;ref&amp;gt;http://www.cafeaulait.org/course/week2/02.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].&amp;lt;ref&amp;gt;http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.http://leepoint.net/notes-java/data/expressions/22compareobjects.html&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.&amp;lt;ref&amp;gt;http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;[http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. &amp;lt;ref&amp;gt;http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html&amp;lt;/ref&amp;gt; &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. Here are some:&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&amp;lt;ref&amp;gt;http://www.research.ibm.com/people/a/alpert/ptch/ptch.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52031</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52031"/>
		<updated>2011-10-15T16:08:17Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. &amp;lt;ref&amp;gt;http://www.cafeaulait.org/course/week2/02.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].&amp;lt;ref&amp;gt;http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.http://leepoint.net/notes-java/data/expressions/22compareobjects.html&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.&amp;lt;ref&amp;gt;http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;[http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. &amp;lt;ref&amp;gt;http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.&amp;lt;ref&amp;gt;http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html&amp;lt;/ref&amp;gt; &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. Here are some:&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&amp;lt;ref&amp;gt;http://www.research.ibm.com/people/a/alpert/ptch/ptch.html&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;/references&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52030</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52030"/>
		<updated>2011-10-15T16:00:23Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. http://www.cafeaulait.org/course/week2/02.html&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack]. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm See [http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm]&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. Here are some:&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.http://www.research.ibm.com/people/a/alpert/ptch/ptch.html&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Classes in Ruby]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/ms228360%28v=vs.80%29.aspx Data Types (C# vs. Java)]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8 Stack and Heap memory]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.cs.unc.edu/~dewan/comp114/f05/notes/12Pointers.doc Primitives vs. Objects]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.ruby-doc.org/docs/ProgrammingRuby/ Programming Ruby]&amp;lt;br/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52029</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52029"/>
		<updated>2011-10-15T15:39:06Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* C# */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack]. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types. See [http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm]&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined.&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class. &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. Here are some:&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Classes in Ruby]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/ms228360%28v=vs.80%29.aspx Data Types (C# vs. Java)]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8 Stack and Heap memory]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.cs.unc.edu/~dewan/comp114/f05/notes/12Pointers.doc Primitives vs. Objects]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.ruby-doc.org/docs/ProgrammingRuby/ Programming Ruby]&amp;lt;br/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52028</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52028"/>
		<updated>2011-10-15T15:37:40Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: /* C# */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack]. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types. &amp;lt;ref&amp;gt;http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined.&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class. &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. Here are some:&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Classes in Ruby]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/ms228360%28v=vs.80%29.aspx Data Types (C# vs. Java)]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8 Stack and Heap memory]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.cs.unc.edu/~dewan/comp114/f05/notes/12Pointers.doc Primitives vs. Objects]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.ruby-doc.org/docs/ProgrammingRuby/ Programming Ruby]&amp;lt;br/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52027</id>
		<title>CSC/ECE 517 Fall 2011/ch3 3h ss</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch3_3h_ss&amp;diff=52027"/>
		<updated>2011-10-15T15:30:54Z</updated>

		<summary type="html">&lt;p&gt;Ssgujar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Primitive objects in object-oriented languages'''&lt;br /&gt;
&lt;br /&gt;
== Introduction == &lt;br /&gt;
&lt;br /&gt;
In any programming language, the [http://en.wikipedia.org/wiki/Data_type data type] refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.&lt;br /&gt;
&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Primitive_data_type primitive data types] refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.&lt;br /&gt;
&lt;br /&gt;
The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.&lt;br /&gt;
* Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc. &lt;br /&gt;
* Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.&lt;br /&gt;
* Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.&lt;br /&gt;
* Strings - Strings represent the sequences of characters or simply any text, e.g. &amp;quot;Hello!&amp;quot;, &amp;quot;9 am to 6 pm&amp;quot;, etc. &lt;br /&gt;
* Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.&lt;br /&gt;
&lt;br /&gt;
Many [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming] languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
&lt;br /&gt;
Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).&lt;br /&gt;
&lt;br /&gt;
Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.&lt;br /&gt;
&lt;br /&gt;
== Primitive objects in different OO languages ==&lt;br /&gt;
=== Java ===&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double&lt;br /&gt;
&lt;br /&gt;
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.&lt;br /&gt;
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack]. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class!! Size&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean || 1-bit&lt;br /&gt;
|-&lt;br /&gt;
| char || Character || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| byte || Byte || 8-bit&lt;br /&gt;
|-&lt;br /&gt;
| short || Short || 16-bit&lt;br /&gt;
|-&lt;br /&gt;
| int || Integer || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| long || Long || 64-bit&lt;br /&gt;
|-&lt;br /&gt;
| float || Float || 32-bit&lt;br /&gt;
|-&lt;br /&gt;
| double || Double || 64-bit&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 20;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I+II);            &lt;br /&gt;
    System.out.println(I.equals(II));    &lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    30&lt;br /&gt;
    false&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.&lt;br /&gt;
&lt;br /&gt;
    System.out.println(INTEGER.TYPE.isPrimitive());&lt;br /&gt;
    System.out.println(BOOLEAN.TYPE.isPrimitive());&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    true&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
    int i = 10;&lt;br /&gt;
    int ii = 10;&lt;br /&gt;
    Integer I = new Integer(i);&lt;br /&gt;
    Integer II = new Integer(ii);&lt;br /&gt;
    System.out.println(I==II);            &lt;br /&gt;
    System.out.println(i==ii);&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    false&lt;br /&gt;
    true&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types. [http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm See [1]]&lt;br /&gt;
&lt;br /&gt;
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:&lt;br /&gt;
 &lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
        int x = 7;&lt;br /&gt;
        object o = x;&lt;br /&gt;
        System.Console.WriteLine(o.ToString());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.&lt;br /&gt;
&lt;br /&gt;
Consider the following example:&lt;br /&gt;
&lt;br /&gt;
    if (t.IsPrimitive)    // where t is the type&lt;br /&gt;
    {&lt;br /&gt;
        // Is Primitive&lt;br /&gt;
    } else if (t == typeof(Decimal))&lt;br /&gt;
    {&lt;br /&gt;
        // Is Decimal&lt;br /&gt;
    } else if (t == typeof(String))&lt;br /&gt;
    {&lt;br /&gt;
        // Is String&lt;br /&gt;
    } else&lt;br /&gt;
    {&lt;br /&gt;
        // Other type&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined.&lt;br /&gt;
&lt;br /&gt;
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values. &lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
|-&lt;br /&gt;
! Primitive Type !! Wrapper Class&lt;br /&gt;
|-&lt;br /&gt;
| string || String&lt;br /&gt;
|-&lt;br /&gt;
| number|| Number&lt;br /&gt;
|-&lt;br /&gt;
| boolean || Boolean&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    var upperCaseString = &amp;quot;APPLE&amp;quot;;&lt;br /&gt;
    var lowerCaseString = upperCaseString.toLowerCase();  // assigns string &amp;quot;apple&amp;quot; to lowerCaseString &lt;br /&gt;
    var s = &amp;quot;Hello&amp;quot;&lt;br /&gt;
    var len = s.length;                                   // assigns value 5 to len&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class. &lt;br /&gt;
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
    puts 10.class&lt;br /&gt;
    puts 7.45.class&lt;br /&gt;
    puts 'hi'.class&lt;br /&gt;
    puts &amp;quot;hello&amp;quot;.class&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
&lt;br /&gt;
    Fixnum&lt;br /&gt;
    Float&lt;br /&gt;
    String&lt;br /&gt;
    String&lt;br /&gt;
&lt;br /&gt;
This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and &amp;quot;hello&amp;quot; are both converted into an object of type String.&lt;br /&gt;
&lt;br /&gt;
Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:&lt;br /&gt;
&lt;br /&gt;
    a=10&lt;br /&gt;
    puts a.to_f  &lt;br /&gt;
    b=20.5&lt;br /&gt;
    puts b.to_i&lt;br /&gt;
&lt;br /&gt;
Output:&lt;br /&gt;
    10.0&lt;br /&gt;
    20&lt;br /&gt;
&lt;br /&gt;
== Advantages of primitives ==&lt;br /&gt;
&lt;br /&gt;
There are several advantages of treating primitives differently from class objects. Here are some:&lt;br /&gt;
&lt;br /&gt;
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.&lt;br /&gt;
*It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.&lt;br /&gt;
*It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of primitives ==&lt;br /&gt;
* The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to  (2^16)-1.&lt;br /&gt;
* The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.&lt;br /&gt;
* Primitives types cannot be extended.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Classes in Ruby]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/ms228360%28v=vs.80%29.aspx Data Types (C# vs. Java)]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.informit.com/articles/article.aspx?p=31755&amp;amp;seqNum=8 Stack and Heap memory]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.cs.unc.edu/~dewan/comp114/f05/notes/12Pointers.doc Primitives vs. Objects]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java]&amp;lt;br/&amp;gt;&lt;br /&gt;
# [http://www.ruby-doc.org/docs/ProgrammingRuby/ Programming Ruby]&amp;lt;br/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ssgujar</name></author>
	</entry>
</feed>