DEV Community

Stan Lo
Stan Lo

Posted on

[Ruby Trick] Retrieve an object's private method without calling its `method`

Goal: Get the bar method

class Foo
  def method; end

  private

  def bar
    "hey!"
  end
end

foo = Foo.new

# foo.method(:bar) will cause error cause it's been overridden
# foo.public_method(:bar) won't work cause :bar is private

method_method = Object.method(:method).unbind
bar_method = method_method.bind(foo).call(:bar)
bar_method.call #=> "hey!"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)