user3007294 user3007294 - 1 year ago 63
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?


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download