Delegation in Ruby

This is my first article in http://railsmagazine.com, it was published in issue 1, so basically I’m just republishing it here again.

“Separate changeable parts from others that remain the same” and “composition is preferred to inheritance” are 2 common design principles when you start designing in OOP world. However and while the first seems to be logical, a one might wonder why it’s preferable to use composition over inheritance, and that’s a logical question, lets answer it via an example:

Let’s suppose that we have a Robot that has a heat sensor, a one would write a very simple UML:

This design has several drawbacks:

1.There is a strong probability to have another type of robots that don’t have heat sensors(breaks the first design principle: separate changeable code from static one).
2.Whenever I want to modify anything related to the heat sensor, I have to change the robot class(breaks the first design principle).
3.Exposure of heat sensor methods to in Robot class.

Let’s enhance this class a bit:

Well, now this is an inheritance based design and it solves the first problem, but it’s still incapable to solve the other 2 problems related to the heat sensor. Let’s do another enhancement:

Now this is a typical design, based on composition rather than inheritance, where we could solve the above 3 problems, and moreover we gained a new thing: we can now abstract the HeatSensor for future uses.

Now what’s delegation?

Delegation is the process of delegating functionality to the contained parts.
If you look carefully at the previous figure, you will notice that the VolcanoRobot is still having the 3 methods that are related to the sensor, well those are a wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).
Delegation comes along with composition to provide a flexible neat solutions like the one we had above, and also it serves the principle “separate changeable code from static one” ,but that also comes with a tax: a need of wrapper methods, and extra time needed in processing because of the call of these wrapper methods.

Ruby and delegation

Now let’s have a code example:
We have a multi purpose Robot that has an arm and a heat sensor, the robot does several jobs, like packaging boxes, stacking them and measuring the heat.
we will use composition and delegation as follows:

As you can see, i have 3 wrapper methods(stack,package and measure_heat) in Robot class that are doing nothing but to call the contained objects corresponding methods.
This is really a nasty thing, specially when there are lots of contained objects.
However there are 2 libs that comes to the rescue to in ruby, Forwardable and Delegate. Let’s check them one by one.

Forwardable lib

Forwardable lib is library that supports delegation, it has 2 modules Forwardable and SingleForwardable:

Forwardable module

The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.

def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.

def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.

Let’s refactor our robot example to make it Forwardable module:

Well, that’s a neater solution as you can see.

SingleForwardable module

The SingleForwardable module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.

Delegate Lib

Delegate lib is another lib that provides delegation, i’ll explain 2 ways to use it:

DelegateClass method

Use the top level DelegateClass method which allows you to easily setup delegation through class inheritance. In the following example, I want to make a new class called CurrentDate, which holds the current date and some extra methods, at the same time I’m delegating to normal date objects:

SimpleDelegator class

Use it to delegate to an object that might be changed:

As you can see, we made 2 objects and then delegated to them consequently.

What about Rails?

Rails adds new functionality called “delegate”:
Which provides a delegate class method to easily expose contained objects’ methods as your own. Pass one or more methods (specified as symbols or strings) and the name of the target object as the final :to option (also a symbol or string). At least one method and the :to option are required.

go to your console and create a dummy project ,then cd to that project, and fire the rails console:

I strongly urge you to check the whole provided examples in rails API documetation,to check also how to use this effectively with ActiveRecord.

Before I finish this article I want to share you the code of delegate method form rails API documentation, I’ll add some comments on the code to explain you what is going on:

That’s it for this article, we have covered 5 points:

1-Composition vs inheritance.
2-What delegation is, and why it’s used.
3-Ruby Forwardable lib.
4-Ruby Delegate lib.
5-Rails delegate method.

C++ passes by reference, Java and Ruby don’t

I got a lot of comments for the previous article, that was explaining how Ruby passes by value, just like Java does.

I thought that showing a simple example implemented in C++, Java and Ruby will clarify the idea. In the following lines, we will make swap functionality in 3 languages, and demonstrate that neither Java nor Ruby passes by reference.

C++

Output:

Java

Output:

Ruby

Output:

As you can notice, in c++ example, passing by reference, will do the swap successfully.
Java and Ruby both don’t pass by reference, instead they pass a copy of the reference, which is a value finally, and so the swap fails, as swapping the copies doesn’t swap the original passed objects.

Please note also that in Java, primitive types are passed by their values directly and no need for any kind of references copies.The same case applies for Ruby, with immediate types(int, char…).

According to the previous 2 facts, we conclude that neither Java nor Ruby passes by reference, instead, both pass by value.

I think that fact that Ruby MRI is using C means they can’t use references, and so they are using pointers, and that explains why swap fails.

I hope that the idea is clear now.

Ruby, pass by value or by reference?

It’s a basic question that I myself had a problem with when i started using Ruby: Does Ruby pass by value or by reference?
Well, if you want a direct answer, then: Ruby passes by value. It’s a similar behavior of what Java does.

Let’s prove it via examples:
Update: this example was passing integers, and it turned out that even everything in ruby is an object, but immedaite values are passed directly by their values, so i changed this example to let it pass strings instead.

Let’s pass an argument to a method and check what goes on:

As you see, we defined a method ‘change’ that takes a parameter ‘x’, changes it value and then returns it back. Then we invoked that method on the argument ‘y’ which had the value ‘3’, and kept having the same value after the method invocation.
This simple example proves that the argument is not passed by reference, otherwise the value of ‘y’ would rather changed to ’10’ after the method invocation.

Now let’s take another example:

In this example, the passed argument value ‘hello’ has changed to ‘fello’, and thus it proves that the argument is not passed by value, otherwise the value of ‘s’ would kept having the same value ‘hello’.

Thus it’s not by value, neither by reference, then what is it?

As you know, everything in Ruby is an object, and thus, doing:

means: assign a reference(a place in memory that points to referenced value. In other words, it’s a place that holds the memory address of the referenced value) of the string ‘somthin’ to the variable named ‘val’, and normally when working with the variable ‘val’, it means we are working on it’s referenced object ‘smthing’.

But when invoking a method:

Things change a bit, as Ruby passes a copy of the ‘val’ reference itself(which is the memory address of the referenced object), not it’s referenced object, to the method Foo, and that copy will still reference the same object ‘smthing’ as the variable ‘val’ does.
This is called: Pass by Value, a copy of a reference to an object is passed, and so, not the referenced object itself is passed, neither the argument itself.
Then Ruby passes by value. Some ppl like to call it “pass by reference value”, but that’s not standard afaik.

That explains what goes in both examples, as in the first example the value of the argument ‘y’ didn’t change due to the fact that we are not passing the reference ‘y’ itself, instead a copy of it, and thus, when its copy referenced another object(via assignment operator), the original variable ‘y’ kept referencing it’s object, the object with value ‘3’ in our case. As for the second example, the argument ‘s’ changed due to the fact that its passed copy is still referencing the same object ‘hello’, but the operator [] changed the referenced object value, and thus got a new value ‘fello’.

I hope the idea is clear now, if not, please don’t hesitate to comment.

Update:
I have blogged a new article explaining passing by reference and value in 3 languages c++, java and ruby

The power of JRuby

It’s true that I’m not the qualified guy to talk about Java’s power,as it has been 2 years since i last practiced it, but i feel like i have to communicate my thoughts to the people that didn’t give JRuby a trial yet, and why they should do so.
If you never worked with Java before, then don’t panic, cause in these article i would list several reasons why JRuby is so powerful even if you don’t know anything about Java.
Lemme start listing all the points that makes me feel the power of JRuby; the order here is irrelevant as i do believe that every point listed bellow has somehow the same rank that others might have:

1- Mixing the power of Java with the power of Ruby.
2- A faster(if not the fastest) Ruby implementation.
3- Native Threads.
4- Support for Foreign Function Interface(FFI).
5- Make use of the JVM (HotSpot).
6- Have a great community and support.

Mixing the power of Java with the power of Ruby

There are thousands of Java packages that are ready for you to use, and according to TIOBE, Java is continuing to be the most popular language, so why don’t you make use of the existing Java packages, and use them inside your code?
For example, you can use the swing package(a very powerful GUI package) inside your ruby code, the following snippet of code is taken from the samples folder in the JRuby distribution:

You can also reference ruby code inside Java code, examples could be found here.

A faster(if not the fastest) Ruby implementation

JRuby team consider it a bug if they are slower on something than MRI, thus they keep enhancing the performance of JRuby.
According to Antonio Cangiano, the guy behind the great ruby shootout here and here:

Ruby 1.9 and JRuby are very close, respectively 2.5 and 1.9 faster than Ruby 1.8.7 (from source) on these benchmarks.

Surprisingly JRuby was slower than ruby 1.8.6 last year, but now it’s competeing 1.9 in terms of speed.
Charles Nutter the JRuby team leader commented on that saying:

I’m looking forward to seeing another update once JRuby finishes 1.9 support, since these JRuby numbers don’t reflect execution and library optimizations 1.9 provides. I expect that JRuby in 1.9 mode will perform much closer to Ruby 1.9.

Until then, it’s good to hear we’re the fastest 1.8 implementation. Thanks again!

Native Threads

The current ruby interpreter which is called MRI supports green threads, as opposed to JRuby which supports native threads.
Green threads are managed by VM, not by the operating system, and thus, by using them you lose a significant power called “concurrency” which is available to multi core processors, that’s because the VM will continue to use one core to serve the whole threads, as opposed to native threads which will use the full power of multi core processor, by being assigned to the available cores.
In general an application might be IO-bounded(lots of IO operations, like logging and database related ones) or CPU-bounded(lots of computation), and while green threads are useful for the IO-bounded applications, they are not useful for the CPU-bounded ones.
A CPU-bonded applications consumes the CPU, and thus you can increase the speed of your program by having multi core processor, but thus you need native threaded applications, to make use of the available cores.
JRuby comes to rescue as it supports native threads, and thus you have full concurrency when you have multi core processors.

Support for Foreign Function Interface(FFI)

According to wikipedia a Foreign Function Interface (or FFI) is :

A mechanism by which a program written in one programming language can call routines or make use of services written in another.

Why would a one need that? well many gems that we use like Rmagic,Hpricot and ruby-prof uses C extensions, either because of performance or because of the ready existing libs related matters.
Well that was causing problems for JRuby users as they couldn’t run those gems that have C extensions, and also for gem developers who had to maintain 2 versions of such gems to let them work for both MRI and JRuby.
That was a kind of disaster till Charles announced that FFI is available for ruby.
So now when you need to have C code inside ruby, then it’s highly recommended to use the FFI gem to save yourself having dual code, and also to make your code work on different ruby implementations.

Make use of the JVM (HotSpot)

Since Sun has announced it’s open source strategy, and lots of optimization work was done for the JVM(HotSpot), the reason behind these optimizations was the fact that many languages is adopting Java to be the hosting language for them, and thus having JVM as an open source technology helped to optimize it to better serve these languages. Some of these languages are: JRuby, Groovy, Scala and Clojure.
So you might be wondering “How this will affect me?”, actually it will affect you indirectly cause once you have a better JVM, it means you have a faster JRuby implementation, and a better management for your memory, as the JVM is considered to have the best garbage collector.
Also you might be able one day to work with other languages(Clojure for example) directly in your ruby code.

Have a great community and support

JRuby has a very nice community, and the guys behind it are very helpful and open to different opinions, just log to #JRuby channel on the FreeNode on IRC, or subscribe to mailing list and send your questions, and you will get the minimum support to let you go.
What i like about this community is their love to the Ruby community, they like to help any rubiest, they even worked with Merb(merb 2 is the core of Rails 3) guys to provide a better performance for merb users.
The current active JRuby contributers are: Charles Nutter, Tom Enebo, Wayne Meissner, Marcin Mielzynski and Nick Sieger, and here some of the past contributers: Ola Bini and Vladimir Sizikov

I hope that i could deliver some of the good points about JRuby, and would like really to have your comments, and what might be also missing from those points. You can find bellow a list of references.

References

*JRuby: What, Why, How…Try It Now by Charles Nutter and Tom Enebo

*JRuby: The Pain of Bringing an Off-Platform Dynamic Language to the JVM by Charles Nutter

*Charles Nutter blog

Update 1
The snippet of code was updated as a respond to Collin’s note

Ruby symbols

I keep seeing many programmers from different backgrounds are unable to get what Ruby symbols are, and though I do know that there are many great posts regarding this topic, and actually my intent is not to increase them by one 🙂 , but I feel I have to clear few points regarding them.
So I’m trying to answer 2 important question here: What are Ruby symbols? and When to use them?

What are Ruby symbols?

Well, according to the API documentation:

Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :”string” literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

Let’s walk over this long quote, point by point, but let’s first list all the points it has:

1-Symbol objects represent names and some strings inside the Ruby interpreter.
2-They are generated using the :name and :”string” literals syntax, and by the various to_sym methods.
3-The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

I’ll start with the 2nd point then get back to the rest, just before I do, please fire your irb:

We can create a symbol with various ways:

That was the easy part, now let’s get back to the first point, it says: “Symbol objects represent names and some strings inside the Ruby interpreter.” , what does that mean exactly?

In computer science there is a term called: Symbol table, where the compiler or the interpreter of the language stores all the identifiers of a source code in that table to reference them -specifically to be referenced by the Abstract Syntax Tree(AST).
Actually the data structure that represents the symbol table varies from one interpreter to another, but what we care for is Ruby, in Ruby, the symbol table stores various things like method names and symbol names(we will check why Ruby does so later on), and the value of a symbol is a unique integer value, that can’t be changed.

Now let’s take more in depth example, let’s explore the symbol table:

As you can see, when we defined the class ‘Dummy’ and more specifically when we defined the ‘hello_world’ method, it was added to the symbol table.
Let’s take another example:

Now let’s take the last point : “The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.” ,so: Fred is :Fred wherever you see it and no matter what the context it comes in:

When to use Ruby symbols?

Well, this might be the one million dollars question, and that’s initially why i wrote this post for. You also might be wondering, why have Matz chosen to give us this low level introspection in the language by allowing me to work with the interpreter stuff?

The answer is divided in 2 parts:

1- Efficiency. 2- Metaprogramming(reflection).

Efficiency

We will talk about efficiency at first place,so let’s check this snippet of code:

The snippet of code above is really costive, in terms of memory and efficiency:
1-Comparing 2 strings is costive, specially when the 2 strings are long.
2-Reserving “changeable” amount of memory, 16 bytes in our case to instantiate “Khaled alhabache”.
3-The GC would have to clean this “Khaled alhabache” later on.

What about doing :

Now what we did is:
1-Comparing 2 integers(the value of a symbol is integer) which is cheaper.
2-Reserving memory 4 bytes for :”Khaled alhabache” symbol, cause a symbol is an integer finally.
3-The GC would not have to clean this :”Khaled alhabache” symbol, cause symbols don’t get deleted till program exits.

So use symbols as much as you can, and avoid using stings as much as you can, but take extra care of defining thousands of symbols, cause as mentioned: symbols don’t get deleted till program exits, and thus they stick in memory.

Metaprogramming and symbols

Well working with metaprogramming in Ruby is really nice, you can do something like:

Without symbols, you would never be able to use reflection techniques like ‘send’, otherwise how can you invoke methods dynamically?, also without symbols, you would never be able to use introspection techniques like ‘respond_to?’

Update, a respond to readers comments:
It’s true that you can do something like :

But what’s happening is that Ruby is casting it for you, but why to reserve extra memory to send it as a string?

For guys who are objecting on memory efficiency with symbols, I strongly recommend reading this post also.

I hope I could help you understand what Ruby symbols are and why they are used for, specially of you who are coming from other programing backgrounds.

Ruby and Metaprogramming

According to wikipedia, Metaprogramming:

is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at runtime that would otherwise be done at compile time.

Well, nice to hear cause Ruby is a lang that supports Metaprogramming effectively, and might be the best in that field. If you want to explore more on that topic, and how ruby can help you, then check this list of posts i wrote recently, i hope you will enjoy them:

If you have any question regarding this topic, please don’t hesitate to contact me, i would really be pleased to help you.

Ruby and Internal DSLs

A Domain-specific language(DSL) is a computer language that’s targeted to a particular kind of problem, rather than a general purpose language that’s aimed at any kind of software problem. Domain specific languages have been talked about, and used for almost as long as computing has been done. Regular expressions and CSS are 2 examples of DSLs.

Any software language needs a parser and an interpreter(or compiler or a mix), but in DSLs, we have 2 types: external ones which need parsers and interpreters, and internal ones which rely on the hosting language power to give the feel of a particular language, and thus they don’t require their own parsers.

Ruby is a very convenient language for writing internal DSLs, it has several powerful techniques that enables you easily to write internal DSLs, and many famous products that we use are nothing but internal DSLs: Haml, Builder and Rake .

Lemme show you a very simple example on how an internal DSL might look like using ruby:

As you can tell, this is a very basic internal DSL, written to describe basic tasks for a robot.
There is one task at the moment called ‘stack’ where the robot should do 2 things: fetch the box, and then package it.
Several ruby techniques are used to bring this basic DSL:
1- Blocks: everything between ‘do .. end’ keywords.
2- Parenthesesless methods: like ‘lock’ and ‘seal’.
3- Passing hash values as method arguments without the need of using curly braces: like doing ‘pick :speed => ‘slow’,:height => 15′.

Now all i need is a simple functionality to execute this simple internal DSL:

And the output:

In addition to the 3 points we mentioned earlier, another 2 ones should be added, as they are the heart of the above executer:

4- Reflection techniques: the one we used inside the class method ‘start’, exactly this line “new.instance_eval(&block)”.
5- method_missing: all undefined methods are received by ‘execute’, the alias of method_missing.

As i mentioned earlier, this is a very basic internal DSL, if you are looking for an advanced article covering a more advanced one, then don’t hesitate to check this rich one by Daniel Spiewak.

Ruby callbacks

This blog post is about ruby’s callbacks(hooks): what are the available ones,and how practically we can use them?

method_missing

obj.method_missing(symbol [, *args] ) => result might be the most famous hook in ruby, and is being used a lot by ruby developers :

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior.

Here is a simple example where the user can mix colors using the mix method :

Now, how about letting the user do something like: ‘c.greenAndBlue’ or ‘c.grayAndYellow’ ?, let’s see how to do so:

const_missing

const_missing : invoked when a reference is made to an undefined constant.

I will use it to show the user a more informative message when he tries to use a non existing constant:

included and extended

included and extended are fired when the module is included or extended :

However let’s move to a more practical use, if u look at the module documentation, you will find the following definition:

A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not.

Well, as you can see, you can’t include the module methods inside your class, then what to do?
I saw some people use a nice trick to do so, they split their module into 2 inner modules, one called InstanceMethods and the other called SingletonMethods, then they include the former, and extend the later, look at the following snippet of code :

method_added and singleton_method_added

method_added and singleton_method_added are another 2 callbacks that are fired when a new instance or singleton method is added.
In the code snippet bellow, I’m trying to prevent a developer from monkey patching(reopen) my colors class:

method_removed and method_undefined

method_removed: fired when an instance method is removed.
method_undefined: fired when an instance method is undefined.

singleton_method_removed and singleton_method_undefined

singleton_method_removed: fired when a singleton method is removed.
singleton_method_undefined: fired when a singleton method is undefined.

inherited

inherited is called when some class is being inherited:

A practical use will be in preventing subclasses from being created :

Well, that’s all for this post. The next post series will be on writing internal DSLs using ruby.
See you then…..

Ruby reflection 2

This is the second post related to ruby’s reflection API, the previous post was an extensive intro to this topic. While the current one will be lighter somehow, it would require you to focus a bit more on the content.
Here we go:

Setting, getting and removing instance variables :

The code above could be written in a simpler way, let’s define another attribute ‘v’ for example :

Now, let’s undefine the instance variable ‘i’

Setting, getting and removing class variables :

As instance_variable_get and instance_variable_set, there are another variations applied to class variables, but unfortunately they are private in ruby 1.8, so let’s use class_eval to bypass that:

Setting, getting and removing constants :

How about constants?

define_method

Now let’s move to a new topic:
Define a method dynamically using define_method:
As the API tells :

Defines an instance method in the receiver. The method parameter can be a Proc or Method object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval, a point that is tricky to demonstrate because define_method is private.

When using a block, the block params will be the method params:

Let’s use it to redefine the ‘attr_access’ in another way rather than the way that was defined in the previous post

One limitation to ‘define_method’ is that: it always creates instance methods, thus if we want to use it to define class methods, then we need to invoke it on the singleton class, let’s define the ‘cattr_access’ method:

Notice how i defined the singleton_class as a local variable, it could be defined using a method, just like what we did in the previous post, however, notice: how complex it became to use the define_method to define a class method, i wouldn’t encourage at all such a complexity.

Undefining methods

How about undefining methods? That can be accomplished in 2 ways: either by using the ‘undef’ statement, or using the private ‘undef_method’ method:

Alias chaining

One last thing that deserves mentioning here: is the ‘alias_method’, it’s being used to have alias chaining:
1- Copy the original method and give it an alias to be used later.
2- Create a new method with the same name of the original one, do whatever changes you need, and use the alias to invoke the original method somewhere inside the new one.
Before i show you the example i have to mention the ruby statement ‘alias’ which can be used as ‘alias_method’ :

I hope you liked this post, please don’t hesitate to notify me about hidden mistakes or suggest new stuff.
I’ll blog on using ruby’s hooks(callbacks) in the next blog post, stay in touch…..

Ruby reflection

If you are here, then most probably you want to know more about ruby reflection interface. Well that’s true, but I always find myself in need to explain few things before I get started with my posts, and this time I find myself in need of explaining few things related to ruby’s OOP.

I’m pretty sure that you always heard that “in ruby: everything is an object.” , but have you ever thought of that carefully?
The first thing that comes to a one’s mind is something like :

But have you thought of your class as an object? Well that seems odd, but that’s how ruby works:

What does the above snippet of code mean exactly?
It means 2 things : Foo is a constant and that constant holds(refers to) an object of Class type.

Let me prove that 2 you:

As you can see, I got a warning because I tried to initialize the constant Foo again.

So ,when you define some class ‘Foo’ in ruby, all you are doing is:
1-instantiating an object of type Class.
2-initializing a constant Foo that refers to that created object .

So bear in mind that when I say “object” ,then I do mean any object; an object of Class type, or any object of any type.

Now, let’s move to another point. What about the ‘Singleton Class’, did you have the chance to work with it before?
Simply it’s the class that holds all singleton methods of an object, whether it’s a class object , or any other object.

Let’s start by defining 2 class methods (a class method is nothing but: a singleton method of an object of Class type) :

You could also have written that in this way:

The above inner class mentioned with “class << self" is what we call : a singleton class. Let's define a method that returns back the singleton class for us :

Now try this :

As you can see, the singleton class is the class that holds all singleton methods. We will use the singleton class later in this series, so keep the concept in mind. Let's now get back to our topic on ruby's reflection api , i will introduce 3 methods in this post: eval , instance_eval and class_eval.

eval

‘eval’ is a method that evaluates a ruby string :

eval can also work in the scope of bindings ; a binding is an object that encapsulates the execution context at some particular place in the code and retain this context for future use. Look at this example of using bindings with eval :

Also can work with proc objects :

instance_eval

This method works in the context of the object :

And could be used to define singleton methods :

you can pass it a block instead of the string :

class_eval

Evaluates a string or a block in the context of the receiver

And it defines instance methods when called on some object

And as instance_eval, a block instead of the string could be passed

You can use class_eval to dynamically use private methods, for example to use the private method ‘include’:

Now let’s make use of our knowledge,let’s try to redefine the attr_accessor method in our way, I will make a similar method called attr_access :

in a similar way we can define class attribute accessors :

Or with we can use the singleton class :

And in both cases we can do :

Give it a try and try to define attr_reader and attr_writer for both object and class variables.

I think it’s enough for this post, the next post will contain more methods to look at. See you then.

Update 1: fixing some typos.
Update 2: second part is here.