Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is splat argument in ruby not used all the time?

Tags:

ruby

splat

I know splat arguments are used when we do not know the number of arguments that would be passed. I wanted to know whether I should use splat all the time. Are there any risks in using the splat argument whenever I pass on arguments?

like image 456
poorvank Avatar asked May 19 '13 12:05

poorvank


1 Answers

The splat is great when the method you are writing has a genuine need to have an arbitrary number of arguments, for a method such as Hash#values_at.

In general though, if a method actually requires a fixed number of arguments it's a lot clearer to have named arguments than to pass arrays around and having to remember which position serves which purpose. For example:

def File.rename(old_name, new_name)
  ...
end

is clearer than:

def File.rename(*names)
  ...
end

You'd have to read the documentation to know whether the old name was first or second. Inside the method, File.rename would need to implement error handling around whether you had passed the correct number of arguments. So unless you need the splat, "normal" arguments are usually clearer.

Keyword arguments (new in ruby 2.0) can be even clearer at point of usage, although their use in the standard library is not yet widespread.

like image 114
Frederick Cheung Avatar answered Sep 17 '22 03:09

Frederick Cheung