almo
almo

Reputation: 6367

Rails remove subarray from array

In my Rails 5 app I have something like this:

a = [1,2,3]

a.map do |entry|
  entry.delete if condition == true
end

This removes the entry if the condition is true.

Now I have this:

a = [[1,2],[2,3],[3,4]]

a.map do |entry|
  entry.delete if condition == true
end

This loops through a but now entry is an array and delete should remove the entire entry but instead I get:

wrong number of arguments (given 0, expected 1)

Dos anybody know how I can loop through an array of arrays and remove an entire subarray?

Upvotes: 0

Views: 846

Answers (2)

Vishal
Vishal

Reputation: 818

instead of using map you should use flat_map see: https://apidock.com/ruby/Enumerable/flat_map

Upvotes: 0

Muhammad Umair
Muhammad Umair

Reputation: 312

Try this: a.delete_if {condition}

For example:

a = [[1,2],[2,3],[3,4]]
a.delete_if {|entry| entry[0] == 1 } 
# returns [[2, 3], [3, 4]] 

Upvotes: 5

Related Questions