Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby method that returns itself

I am doing some reflection, and ran into an unexpected road block.

Is there an object method in ruby (or rails) that returns itself

ruby-1.9.2> o = Object.new  => #<Object:0x00000104750710>  ruby-1.9.2> o.class  => Object  ruby-1.9.2> o.send :self NoMethodError: undefined method `self' for #<Object:0x00000104750710> 

What I want

ruby-1.9.2> o.send :self  => #<Object:0x00000104750710>  

Is this built in? Or do I need to extend Object (It always gets me nervous opening up Object):

class Object    def itself     self   end  end 

And then so:

ruby-1.9.2> o.send :itself  => #<Object:0x00000104750710>  

Ok, some background on what I am trying to achieve. I have a generic table helper in my rails app, and you call if like so:

  render_list @person, [{field: :name, link_to: :itself},                         {field: {address: :name}, link_to: :address}] 

I was struggling on the right way to call :itself -- but i'm thinking that my patch is the way to go.

like image 655
Jonathan Avatar asked Jun 10 '11 15:06

Jonathan


People also ask

What is self method in Ruby?

self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.

What does Ruby method return?

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.

What is an instance method Ruby?

In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class.

What is class << self in rails?

Outside of any class/module/method definitions, self is a main object of the class Object . >> puts self, self.class main Object. Inside a method within a class, self is the object of that class.


2 Answers

Yes! If you have Ruby 2.2.0 or later, you can use the Kernel#itself method.

You can see the extensive discussion of this feature here: https://bugs.ruby-lang.org/issues/6373. The patch was submitted by Rafael França in message #53.

You can see it in the official Ruby source by looking in object.c.

like image 89
David Grayson Avatar answered Sep 17 '22 13:09

David Grayson


There is a discussion about adding such method: http://bugs.ruby-lang.org/issues/6373

like image 31
Alexey Avatar answered Sep 17 '22 13:09

Alexey