user3007294 user3007294 - 5 months ago 6
Ruby Question

Select all but current in array

a = [1,4,1]
total = []

a.each do |num|
total << a.select {|x| x != num}
end

p total => [[4], [1, 1], [4]]


I am hoping to select all the other elements inside an array except the current element. The above works fine when there's no duplicates, but when there is, the output is incorrect. In this case, the output should be:

[[4,1], [1, 1], [1,4]]


I tried using each_with_index and targeted the index instead of the number but ran into the same issue. Any ideas? Something other than select?

Thanks

Answer

I'm not much of a Ruby developer, so apologies if this isn't idiomatic, but give this a shot?

a = [1,4,1]

total = a.each_index.map { |index| a[0...index] + a[(index+1)..-1] }

p total