On Mon, May 30, 2011 at 9:55 AM, Ilias Lazaridis <ilias / lazaridis.com> wrote:
> On 27  07:51, Ilias Lazaridis <il... / lazaridis.com> wrote:
>> On 26  13:31, Roger Braun <ro... / rogerbraun.net> wrote:
>>
>> > 2011/5/26 Ilias Lazaridis <il... / lazaridis.com>:
>>
>> > > What I'm looking for:
>>
>> > > how can I detect WHERE the object was instantiated?
>>
>> > This seems to do what you need.
>>
>> >http://snippets.dzone.com/posts/show/2787
>>
>> > See also here:
>>
>> >http://www.ruby-doc.org/core/classes/Kernel.html#M001397
>>
>> This one could lead to a solution, at least a temporal one.
>>
>> I can retrieve from the Kernel.caller the call stack, and from there
>> the information <main>.
>>
>> How can I user the string "<main>" or "<class:MyClass>" to retrieve
>> the actual object of main or MyClass?
>
> for "class:MyClass'
>
> obj = Kernel.const_get("MyClass") #=> returns object which represents
> MyClass
>
> for "main"?
>
> How can I retrieve the "main" object?

If you are in the top level, then self is that object:

puts self
puts self.class

If not, here is one way:

class Test
  def give_me_main
    eval 'self', TOPLEVEL_BINDING
  end
end

o = Test.new.give_me_main
puts o
puts o.class


Jesus.