Method for splitting array into (element => remaining elements) pairs

I got another idea. Here is this :

a = [1, 2, 3]
a.combination(2).with_object({}) { |ar, h| h[(a - ar).first] = ar }
# => {3=>[1, 2], 2=>[1, 3], 1=>[2, 3]}

A modified version of Piotr Kruczek .

[1,2,3].permutation.with_object({}) { |(k, *v), h| h[k] = v }
# => {1=>[3, 2], 2=>[3, 1], 3=>[2, 1]}

I've come up with something like this:

[1,2,3].permutation.to_a.map{ |e| [e.shift, e] }.to_h

However this has a flaw: it assigns the same key many times, but since you don't care about the sequence of the elements inside this might be a "good enough" solution.

Tags:

Ruby