Ruby is a dynamically typed language and it's also duck-typed, when you decide to use duck-typing features you should probably just mention it in documentation and call it, if it's not there it will crash, think about it carefully, pretend you could check that get_data
exists(and you could as we shall see later), what do you want to do ?
Do you want to return nil
? if foo
should return a value you could return nil
but you'll risk your users a NoSuchMethodError for nil:NilClass
, if foo
is meant to return nothing(semantically void) then nil
is no option to you, do you want to raise
an Error ? well probably the very reason you want to check that get_data
exists is to protect against type errors but now you raise another error, maybe you want to raise a specific error but honestly NoSuchMethodError : method get_data missing in someObject:SomeClass
is specific enough in my opinion.
With that in my mind I'm going to show you how to check for it anyway, there are many ways, a very simple way :
def foo
begin
var = @obj.get_data
rescue NoMethodError
// handle the case where get_data does not exist
end
end
A probably better way is to check that obj
has get_data
in initialize
using the above way or this :
def initialize(obj)
if(!obj.respond_to? :get_data)
//handle the case where get_data is not defined
end
end
The problem with the last code is that all you check is obj
having get_data
, you don't check whether it has proper signature, if you want to check that you can :
def initialize(obj)
unless(!obj.respond_to? :get_data)
params = obj.method(:get_data).parameters
//if get_data for example takes x,y then params will be `[[:req,:x],[:req,:y]]`
end
end
Of course you can't check that get_data accepts specific types because ruby is dynamically typed.
If you also want to check the method's return type after you check for its existence and parameters you can call it because it's safe and check the return type like this :
a=obj.get_data
if(a.is_a? SomeClass)
//good
end
If you want to check that get_data returns nothing(semantically void method), well in ruby returning nil
is analogous to void but so is the failure to return a value so you can't check for that.