tags:

views:

34

answers:

1

In Ruby 1.8.7 I can do the following in order to get the subject of a binding object:

binding.eval("self")

However, in Ruby 1.8.6, the eval method is private, so I expose it like this:

class Binding
  public :eval
end

Which seems to work fine, however, binding.eval("self") returns the binding itself, not the subject of binding.

How can I get the subject of a binding in Ruby 1.8.6? The solution doesn't need to pretty - it just needs to work until we can upgrade to 1.8.7.

+1  A: 

I'll bet at least a nickel eval('self', abinding) will work:

#!/usr/bin/ruby1.8

class Foo

  def foo
    binding
  end

end

p eval('self', Foo.new.foo)    # => #<Foo:0xb7bfe5ac>

This works because if you pass a binding to eval, it evaluates the string in the context of that binding. self in the context of the binding is whatever self was when the binding was created.

Wayne Conrad
Thanks Wayne. That worked! I'm not sure why though.. Also, it's 1.8.6, not 1.6.
Joel
@Joel, What can I say? Blast my eyes! I added an explanation. Thanks for the check-mark!
Wayne Conrad