Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

ruby

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?

like image 790
Philip Avatar asked Mar 12 '14 01:03

Philip


1 Answers

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.

like image 63
user2864740 Avatar answered Oct 02 '22 04:10

user2864740