I am not sure if an object I pass to a method is of the proper type. I might pass a string to a function that can only handle integers. What about some kind of runtime ensurance? I couldn't see a better option than:
def someFixNumMangler(input)
raise "wrong type: integer required" unless input.class == FixNum
other_stuff
end
Any better alternatives?
Use the Kernel#Integer method to convert the input before using it. It will raise an ArgumentError
when the input could not be converted to an integer in any reasonable fashion.
def my_method(number)
number = Integer(number)
# do something with number, which is now guaranteed to be an integer
end
I recommend Avdi Grimm's new book Confident Ruby for more insight into this.
If you really need to do type checks, then yes, you only have runtime checking. Code in the question is ok. You can also use .is_a?
.
def someFixNumMangler(input)
raise "wrong type: integer required" unless input.is_a?(FixNum)
other_stuff
end
The checks may take different forms. If you expect, say, a string and you call string methods on it (upcase
, gsub
, etc), the code will blow up if anything other than string is passed. Unless, of course, you pass an object that is not a string, but behaves just like one (has the same methods that you call). This is the essence of duck typing.
What if your method looked 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 an argument responds to #to_i
, you don't actually care what its type is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With