DEV Community

loading...

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

st0012 profile image Stan Lo ・1 min read

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

Discussion (0)

pic
Editor guide