DEV Community

Stan Lo
Stan Lo

Posted on

3 1

[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)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay