Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 353
Orcris Avatar asked May 30 '12 21:05

Orcris


People also ask

How does * args work in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

How do you define a method that can accept a block as an argument?

We can explicitly accept a block in a method by adding it as an argument using an ampersand parameter (usually called &block ). Since the block is now explicit, we can use the #call method directly on the resulting object instead of relying on yield .

What's the difference between a parameter and an argument Ruby?

Note the difference between parameters and arguments: Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the function. Parameters are initialized to the values of the arguments supplied.


1 Answers

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
like image 157
Samy Dindane Avatar answered Sep 21 '22 21:09

Samy Dindane