1

I have a class (BaseClass) and a subclass (SubClass) that inherits from the BaseClass. One of the operations I want to perform is to send requests from the Base to the Sub but only if there is a method defined for it. Let me demonstrate this with some code:

BaseClass:

def extract_data extracted_data=Hash.new ['attr1','attr2','attr3'].each do |attr| extracted_data[attr] = self.send("extract_#{attr}") end return extracted_data end 

SubClass:

def extract_attr1 # do something and return a value end 

This works prefectly well if there is a method with that name in defined in the Subclass. If its not defined I will get an error. How can I check that a method is defined in a subclass before calling it?

1 Answer 1

8

Just write as below using Object#respond_to?

extracted_data[attr] = self.send("extract_#{attr}") if self.respond_to?("extract_#{attr}") 
Sign up to request clarification or add additional context in comments.

4 Comments

Some Ruby programmers do not like #respond_to? method, as its certain uses are a sign of chicken typing. In this particular case, #respond_to? seems ok to me, but some might prefer NoMethodError exception handling.
@BorisStitnicky You means self.send("extract_#{attr}") rescue NoMethodError. BTW what is chicken typing ?
In short: do_something() if self.respond_to('some_possible_function')
@Eddie You're missing the question mark in respond_to?.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.