Array of arrays, delete an index based on the contents of the array in the index?

I struggled to learn how to handle arrays of arrays.

Let's say I had this array:

my_array = [['ORANGE',1],['APPLE',2],['PEACH',3] 

How can I find the index my_array containing "apple" and delete this index (deleting the submatrix ['APPLE', 2], because "apple" was copied to the array at this index)?

Thank you, I really appreciate the help here.

+4
source share
3 answers

You can use Array.select to filter elements:

 >> a = [['ORANGE',1],['APPLE',2],['PEACH',3]] => [["ORANGE", 1], ["APPLE", 2], ["PEACH", 3]] >> a.select{ |a, b| a != "APPLE" } => [["ORANGE", 1], ["PEACH", 3]] 

select will return those elements from for which the given block (here a != "APPLE" ) returns true .

+6
source
 my_array.reject { |x| x[0] == 'APPLE' } 
+6
source

I tested this, it works:

 my_array.delete_if { |x| x[0] == 'APPLE' } 
+4
source

Source: https://habr.com/ru/post/1338518/


All Articles