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)
As long as the argument answers #to_i
, you really don't care about its type.
source share