class C1
unless method_defined? :hello # Certainly, it's not correct. I am asking to find something to do this work.
def_method(:hello) do
puts 'Hi Everyone'
end
end
end
So, how to judge whether a method has defined or not?
class C1
unless method_defined? :hello # Certainly, it's not correct. I am asking to find something to do this work.
def_method(:hello) do
puts 'Hi Everyone'
end
end
end
So, how to judge whether a method has defined or not?
Look at the Ruby Object class. It has a
methods
function to get an list of methods and arespond_to?
to check for a specific method. So you want code like this:The Object class has the method "methods": docs
The code you posted works just fine for checking whether the method is defined or not.
Module#method_defined?
is exactly the right choice. (There's also the variantsModule#public_method_defined?
,Module#protected_method_defined?
andModule#private_method_defined?
.) The problem is with your call todef_method
, which doesn't exist. (It's calledModule#define_method
).This works like a charm:
However, since you already know the name in advance and don't use any closure, there is no need to use
Module#define_method
, you can just use thedef
keyword instead:Or have I misunderstood your question and you are worried about inheritance? In that case,
Module#method_defined?
is not the right choice, because it walks the entire inheritance chain. In that case, you will have to useModule#instance_methods
or one of its cousinsModule#public_instance_methods
,Module#protected_instance_methods
orModule#private_instance_methods
, which take an optional argument telling them whether to include methods from superclasses / mixins or not. (Note that the documentation is wrong: if you pass no arguments, it will include all the inherited methods.)Here's a little test suite that shows that my suggestion works: