-2

I read this code that is about quicksort with monkey-patching for the Array class.

class Array
  def quicksort
    return [] if empty?

    pivot = delete_at(rand(size))
    left, right = partition(&pivot.method(:>))

    return *left.quicksort, pivot, *right.quicksort
  end
end

I don't know what the star (*) sign seen at the start of *left.quicksort is. Can't we just use left.quicksort?

sawa
  • 165,429
  • 45
  • 277
  • 381
newBike
  • 14,385
  • 29
  • 109
  • 192
  • If a question is a duplicate and you really want to get some original feedback on it, you should head on over to one of the ruby IRC channels and ask there. You don't even have to have an IRC client, there is web based access here, for example: http://irc.lc/freenode/ruby-lang. That or a ruby subreddit – boulder_ruby Jan 29 '16 at 16:28

3 Answers3

2

The star (in this case) stands for array unpacking. The idea behind it is that you want to get one array with the given elements, instead of array of array, element, array:

left  = [1, 2, 3]
pivot = 4
right = [5, 6, 7]

[left, pivot, right] # => [[1, 2, 3], 4, [5, 6, 7]]

[*left, pivot, *right] # => [1, 2, 3, 4, 5, 6, 7]
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
0

The * takes a list of arguments and splits them into individual elements. This allows you to return one un-nested array even when the left and right themselves return an array.

Regarding can't we just use left.quicksort did you give it a try?

def a()
  return *[1,2,3], 4, *[5,6]
end

def b()
 return [1,2,3], 4, *[5,6]
end

b()
=> [[1, 2, 3], 4, 5, 6]
a()
=> [1, 2, 3, 4, 5, 6]
Paul Rubel
  • 26,632
  • 7
  • 60
  • 80
0

Without the asterisk, you will have three values returned... the first and last value will be a single array with multiple values

[array1], pivot, [array2]

With the asterisk, the array values will be returned as separate components...

array1_value_1, array1_value_2, array1_value_3, ..., pivot, array2_value_1, array2_value2, array2_value_3, ...
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53