In Ruby language source code, lib/fileutils.rb
, method mkdir_p
looks like this when simplified:
def mkdir_p(list, options={})
return *list if options[:noop]
# ...
return *list
end
Both from what I understand about Ruby and from testing, there's no point to the splat here. Is there any edge case where this makes a difference?
Relatedly, if there is no edge case where this makes a difference in output, is the splat completely harmless or does it cause any Ruby interpreter to do additional (unnecessary) work?
There are actually differences between return l
and return *l
; it helps to know what to look for.
One important difference is it makes a copy of the Array or materialized Enumerator - a new Array is returned in all cases.
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 the splat operator will coerce nil
to an empty Array and it will coerce other (non-Array/Enumerator) values to an Array of one element - again, a new Array is returned in all cases.
r = x(nil)
# r -> []
s = x("one")
# s -> ['one']
As such, using return *l
has subtle implications, which are hopefully well-enough covered by the method documentation or otherwise "not surprising" in usage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With