There was a question like this: how to remove negative copies of numbers from an array in the shortest way in ruby .

For example, we have an array [1, 2, 5, -5, -6]

Here -5 is a duplicate minus duplicate 5. On the same example, we get [1, 2, 5, -6]

  • Give an example of what you have already tried to do. - Nakilon

1 answer 1

Using the .each_with_object iterator:

 a = [1, 2, 5, -5, -6] a - a.each_with_object([ ]) { |n, b| b << -n if n > 0 } # => [1, 2, 5, -6] 

With the help of the .select and .map methods:

 a = [1, 2, 5, -5, -6] pa - a.select{ |i| i > 0 }.map{ |i| -i } # => [1, 2, 5, -6] 

Using the .reject and .include methods:

 a = [1, 2, 5, -5, -6] a.reject { |e| e < 0 && a.include?(e.abs) } # => [1, 2, 5, -6]