2

The first line of bin/jekyll of the Jekyll gem uses the following syntax:

$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])

I can't seem to figure out what the purpose of the splat is. Running that line with and without the splat in IRB results in the same ouput "./../lib".

https://github.com/mojombo/jekyll/blob/master/bin/jekyll

Paul Simpson
  • 2,504
  • 16
  • 28

2 Answers2

1

At least in Ruby 1.9.3, both usages of the join method seem to be equivalent. Under the hood, the elements of an array are joined to the path recursively, with special protection against infinite recursion.

Therefore, this works fine:

File.join 'a', ['b', ['c']]

One might argue that the purpose of the splat operator is to eliminate the recursion. The problem is that this:

File.join 'a', *['b', ['c']]

Is equivalent to this:

File.join 'a', 'b', ['c']

In order to eliminate the recursion, you have to flatten the array and then splat it:

File.join 'a', *['b', ['c']].flatten

In the context of a parameter list, the splat operator "removes" the brackets of an array, so to speak. It results in this:

# File.join receives 3 strings as parameters
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib')

As opposed to this:

# File.join receives 2 parameters, one string and one array of strings
$:.unshift File.join(File.dirname(__FILE__), ['..', 'lib'])

More information about the splat operator.

Community
  • 1
  • 1
Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
1

The * flattens the arguments. Equivalent without the splat:

File.join(File.dirname(__FILE__), ["..", "lib"])

Equivalent with the splat:

File.join(File.dirname(__FILE__), "..", "lib")

I guess in this case File.join treats it the same way. But see that the documentation implies they should be flattened. Now, why the author didn't simply write it without arrays OR splats is a different matter.