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

Stan Lo - Dec 13 '19 - - Dev Community

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
. . . . . . . . . . . .
Terabox Video Player