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.
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.
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.
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.
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.
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.
There is a discussion about adding such method: http://bugs.ruby-lang.org/issues/6373
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With