How do I only allow an argument in a Ruby function to be a certain type?

arguments, function, parameters, ruby

Solution

You can't do `def function(Array arg)` like in other languages, but you can replace four lines of your second snippet by a single one:

def function(arg)
  raise TypeError unless arg.is_a? Array
  # code...
end

Problem

For example, if I have ``` def function(arg) #do stuff end ``` how do I only allow `arg` to be an Array? I could do ``` def function(arg) if arg.class != 'Array' return 'Error' else #do stuff end end ``` but is there any better way of doing this?

Original source