Tutorial :aliasing a method results in different objects?



Question:

def foo      "foo"  end    alias foo2 foo  puts "foo2: " + foo2.object_id.to_s  puts "foo: " + foo.object_id.to_s  

In the above example, I expected to see the same object_id output for each method call since they reference the same method. Why do I see different object_id's? When you alias a method in Ruby doesn't the alias refer to the original object, not a copy?


Solution:1

Starting over with a new answer in response to your various comments.

In the example code, you are calling the method, not referencing it. You want to use

method(:foo)  

to actually get the method itself and not the result of calling it.

Also, object_id is not the right way to test if two methods are the same, because method(:foo) returns a new Method object each time. For an analogy that might make this clearer, if you opened the same file twice you would have two distinct file handles even though the underlying file was the same. Instead, I think you want:

method(:foo) ==  method(:foo2)  

which, as you will see if you try it, returns true.


Solution:2

You're calling object_id on the object returned by foo, which is a string created in the method and thus will be different every time. You'd see the same results if you just called foo twice. It returns a new string every time. If you want a constant string, return the symbol :foo instead.

Past that, even though they share the same implementation right now, they are different methods. If you override foo to return the string "bar", foo2 will still keep returning "foo".


Solution:3

Try:

FOO = "foo"  def foo      FOO      end    alias foo2 foo  puts "foo2: " + foo2.object_id.to_s  puts "foo: " + foo.object_id.to_s  

To get the effect you are wanting. "foo" is an expression and it gets evaluated each time the function is called. To see why this is, consider that you could just as well have written:

def foo      "It is now #{Time.now}"      end    alias foo2 foo  puts "foo2: " + foo2.object_id.to_s  puts "foo: " + foo.object_id.to_s  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »