On Tuesday 03 June 2014 16:51:07, Roelof W. [email protected]
wrote:
Sorry,. I read the whole topic again but I cannot find anything about
.instance_methods or do you mean .lookup or ,responds_to.
Then I still not clear to me what I schould do when I see
SantaClaus(SantaClaus.new)
Could I do SantaClaus.lookup SantaClaus.new ?
AFAIR, what you want to archieve is to check whether an Object responds
to a
number of methods, i.e., “implements an interface”. (Please not the
quotation
marks, I’m still not happy with that notion.)
So, suppose your “interface” consists of the methods “method_a”,
“method_b”
and “method_c”, you check whether a given object responds to all three.
The first, simple version can then look like this:
def test_responds_to_my_methods
my_obj = MyClass.new
responds_to_all = true
[ :method_a, :method_b ].each do |method|
responds_to_all &= my_obj.respond_to? method
end
end
The method .instance_methods returns an Array of Symbols, each Symbol
being
one method the object responds to.
You can also pass “false” as parameter to .instance_methods in order to
only
include the methods the class itself defines. This allows you even
better
“interface checking”.
Consider:
class MyPseudoInterface
def method_a
end
def method_b
end
end
MyPseudoInterface.instance_methods(false) # => [:method_a, :method_b]
If you’ve got an object, you need to gain access to the class before you
can
call .instance_methods. You do that using “my_obj.class”, i.e.,
“my_obj.class.instance_methods”.
(Notice the dot instead of the hash in the text: An instance method is
typically written using an hash as separator, e.g.,
MyClass#an_instance_method. Class methods are separated using a dot.)
Putting it all together, you can solve your exercise.
HTH.
--- Eric