Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

For a method that would take an arbitrary amount of parameters, options hash is a de facto solution:

def foo(options = {})
  # One way to do default values
  defaults = { bar: 'baz' }
  options = defaults.merge(options)

  # Another way
  options[:bar] ||= 'baz'

  bar = options[bar]
  do_stuff_with(bar)
end

A good use of splat is when you're working with an array and want to use just the first argument of the array and do something else with the rest of the array. It's much quicker as well than other methods. Here's a smart guy Jesse Farmer's use of it https://gist.github.com/jfarmer/d0f37717f6e7f6cebf72 and here is an example of some other ways I tried solving the spiraling array problem and some benchmarks to go with it. https://gist.github.com/TalkativeTree/6724065

The problem with it is that it's not easily digestible. If you've seen and used it before, great, but it could slow down other people's understanding of what the code is doing. Even your own if you haven't looked at it in a while hah.

Splat lets the argument be interpreted as an array, and you would need an extra step to take it out. Without splat, you do not need special things to do to access the argument:

def foo x
  @x = x
end

but if you put it in an array using splat, you need extra step to take it out of the array:

def foo *x
  @x = x.first # or x.pop, x.shift, etc.
end

There is no reason to introduce an extra step unless necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top