How to call a private method in Ruby
If you want to call a private method in Ruby - for any reason - you can use send, method and instance_eval:
class Foo
private
def bar
puts 'You called bar'
end
end
> foo = Foo.new
foo.bar # this, of course, throws an error
NoMethodError: private method `bar' called for #
from (irb):129
from :0
> foo.send(:bar)
You called bar
=> nil
m = foo.method(:bar)
=> #
> m.call
You called bar
=> nil
> foo.instance_eval { bar }
You called bar
=> nil
Remember you cannot use eval to call a private method:
> eval('foo.bar')
NoMethodError: private method `bar' called for #
from (irb):140
from (irb):140
from :0
Labels: metaprogramming ruby, ruby
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home