Check if a method written inside a Proc is defined?

202 views Asked by At

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 !

1

There are 1 answers

0
tadman On

defined? is used to test if variables are defined or constants exist, not methods per-se.

For that you should use:

1.method(:+)

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:

1.respond_to?(:+)

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 through method_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.