user3007294 user3007294 - 10 months ago 29
Ruby Question

Select all but current in array

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

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

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?



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 = { |index| a[0...index] + a[(index+1)..-1] }

p total