给定一个数组字面量,我想创建一个散列,其中键是数组中的元素,值是包含其他/剩余元素的数组。
Input:
[1, 2, 3]
Output:
{1=>[2, 3], 2=>[1, 3], 3=>[1, 2]}
如果我引入一个变量,这很容易:
arr = [1, 2, 3]
arr.map { |i| [i, arr - [i]] }.to_h
但是对于数组文字,我能想到的唯一解决方案是instance_exec
or instance_eval
,这看起来很黑客:
[1, 2, 3].instance_exec { map { |i| [i, self - [i]] } }.to_h
我是否忽略了内置方法或明显的解决方案?group_by
, combination
, permutation
and partition
似乎没有帮助。