Checking method parameter type

I am not sure that the object I pass to the method is of the correct type. I can pass a string to a function that can only process integers. How about some kind of runtime guarantee? I have not seen a better option than:

def someFixNumMangler(input) raise "wrong type: integer required" unless input.class == FixNum other_stuff end 

Any better alternatives?

+4
source share
2 answers

Use the Kernel # Integer method to convert input before using it. It will raise an ArgumentError when an input cannot be converted to an integer in any reasonable way.

 def my_method(number) number = Integer(number) # do something with number, which is now guaranteed to be an integer end 

I recommend Avdy Grimm's new Confident Ruby book to get a better understanding of this.

+5
source

If you really need to do type checks, then yes, you only have runtime checks. The code in the question is ok. Can you also use .is_a? .

 def someFixNumMangler(input) raise "wrong type: integer required" unless input.is_a?(FixNum) other_stuff end 

Inspections can take many forms. If you expect, say, a string, and you call string methods on it ( upcase , gsub , etc.), the code will explode if anything other than the string is passed. Unless, of course, you pass an object that is not a string, but behaves exactly the same as one (it has the same methods that you call). This is the essence of duck print.

What if your method looks like this?

 def someFixNumMangler(input) input = input.to_i puts "got this: #{input} of #{input.class}" end someFixNumMangler(10) someFixNumMangler('42') someFixNumMangler(File) # >> got this: 10 of Fixnum # >> got this: 42 of Fixnum # ~> -:2:in `someFixNumMangler': undefined method `to_i' for File:Class (NoMethodError) # ~> from -:9:in `<main>' 

As long as the argument answers #to_i , you really don't care about its type.

+3
source

Source: https://habr.com/ru/post/1500726/