Juanito Fatas
Juanito Fatas

Reputation: 9969

Splat operator in Ruby (a quicksort example)

Hello I'm studying some Ruby code. Implement Quicksort in Ruby:

1 def qsort(lst)
2   return [] if lst.empty?
3   x, *xs = *lst
4   less, more = xs.partition{|y| y < x}
5   qsort(less) + [x] + qsort(more)
6 end

Given:

lst = [1, 2, 3, 4, 5]

x, *xs = *lst

I do not know if I understand what line 3 is doing correctly:

From my observation and experiment, this will assign 1 from lst to x, and the rest of lst to xs.

Also I found these two are doing the same thing:

x, *xs = *lst

   is equivalent to

x, *xs = lst

My question is, what's the name of this nice feature (I will edit the title afterwards to adapt)? Then I could study more about this Ruby feature myself. Sorry if it's a duplicate problem, because I don't know the keyword to search on this problem.

Upvotes: 3

Views: 1631

Answers (3)

Victor Moroz
Victor Moroz

Reputation: 9225

This statement

x, *xs = *lst

doesn't make much sense to me, but these do:

x, *xs = [1, 2, 3] # x -> 1, xs -> [2, 3]
x = 1, *[2, 3, 4] # x -> [1, 2, 3, 4]

this usage IMO has nothing to do with parameters, but as others said splat can be (and usually is) used with parameters:

def foo(a, b, c)
end

foo(*[1,2,3]) # a -> 1, b -> 2, c -> 3

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118299

The splat operator in Ruby, Groovy and Perl allows you to switch between parameters and arrays:it splits a list in a series of parameters,or collects a series of parameters to fill an array.

From 4 Lines of Code.

Upvotes: 2

sunny1304
sunny1304

Reputation: 1694

The name of this feature is called splat operator in Ruby.

Upvotes: 6

Related Questions