The closest I can find is In Ruby, how do I check if method "foo=()" is defined?, but it only works if the method is public, even when inside the class block.
What I want:
class Foo
private
def bar
"bar"
end
magic_private_method_defined_test_method :bar #=> true
end
What I've tried:
class Foo
private
def bar
"bar"
end
respond_to? :bar #=> false
#this actually calls respond_to on the class, and so respond_to :superclass gives true
defined? :bar #=> nil
instance_methods.include?(:bar) #=> false
methods.include?(:bar) #=> false
method_defined?(:bar) #=> false
def bar
"redefined!"
end # redefining doesn't cause an error or anything
public
def bar
"redefined publicly!"
end #causes no error, behaves no differently whether or not #bar had been defined previously
end
What is a private method in Ruby? It’s a type of method that you can ONLY call from inside the class where it’s defined. This allows you to control access to your methods. By default ALL your methods are public. Anyone can use them! But you can change this, by making a method private or protected. Why is this useful?
In Ruby language, the Variable is declared and assigned with values. Ruby provides defined method. It checks an expression to check whether it is a variable or assignment or expression or method. If it is not unable to resolve, returns empty or nil. You can also check conditional if expression to return true or false
Try the “safe navigator operator” (Ruby 2.3+) which only calls a method if the variable is not nil. These aren’t as universal as the defined? keyword, but they are more predictable & less prone to errors. You can use defined? to check if a method is defined, but it’s not that practical.
With private you can only do name, with protected you can do object.name. When should you use protected? Only if you have a very specific case, like the equals ( ==) method. The Ruby documentation recommends using private instead of protected whenever possible. “A protected method is slow because it can’t use inline cache.”
Another way is to use :respond_to?
, e.g.
self.respond_to?(:bar, true)
Note that the second parameter is important here - it denotes that :respond_to?
should look for all scope methods including private methods.
You want Module#private_method_defined?
.
class Foo
def do_stuff_if_bar_is_defined
if self.class.private_method_defined?(:bar)
do_stuff
end
end
private
def bar
"bar"
end
private_method_defined? :bar #=> true
end
Foo.private_method_defined? :bar #=> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With