For some reason I store methods in a Proc and I want to check if they are defined.
If I do : defined? 1.+
I get method
in return so I know the +
method is defined.
Now if I store the methods in a Proc : p = Proc.new { 1.+ }
,
I want to know how i can check if the method stored in p
is defined
I have tested defined? p
or defined? p.call
but it's not the attended results ...
Thanks for your help !
defined?
is used to test if variables are defined or constants exist, not methods per-se.For that you should use:
Where if that method doesn't exist you get a
NameError
exception. That's not the best way to test, though, instead there's a much simpler method for it:Where if that method "responds to" that method call it will (usually) return
true
. Since Ruby is a highly dynamic programming language and methods can be made-up on the spot throughmethod_missing
and other tricks, this might not be 100% accurate, but it is for pre-defined methods.Unfortunately once you've wrapped some valid Ruby code inside a
Proc
it's not possible to test any more if it will or won't work without executing it. This means if you have a Proc, it's basically a black box, short of delving in through tricks in the VM, but that's Ruby implementation specific.