Any reason ever for a Ruby method to return a splat list?

In the Ruby lib/fileutils.rb source code, the lib/fileutils.rb method looks like this:

 def mkdir_p(list, options={}) return *list if options[:noop] # ... return *list end 

Both from what I understand about Ruby and from testing, there is no point in splat here. Is there any boundary case where this matters?

Accordingly, if there is no case with an edge where it makes a difference in output, is splat completely harmless or does it force any Ruby interpreter to do extra (unnecessary) work?

+8
syntax ruby
source share
1 answer

There are actual differences between return l and return *l ; it helps to know what to look for.

An important difference is that it makes a copy of the array or materialized Enumerator - in all cases a new array is returned.

 def x(l) return *l end p = ["hello"] q = x(p) q[0] = "world" # p -> ['hello'] # q -> ['world'] u = x(0.upto(2)) # u -> [0, 1, 2] - Enumeration is forced 

Another difference is that the splat operator will force nil to an empty array and will force other values ​​(non-Array / Enumerator) to an array of one element - again, in all cases, a new array is returned.

 r = x(nil) # r -> [] s = x("one") # s -> ['one'] 

Thus, the use of return *l has subtle consequences, which, we hope, are fairly well described in the documentation of the method or are otherwise not β€œsurprising” in use.

+8
source share

All Articles