Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Arrays, delete an index based on the contents of the array at the index?

Tags:

ruby

I've been struggling learning how to deal with arrays made up of arrays.

Say I had this array:

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

How would I go about finding the my_array index that contains 'apple' and deleting that index (removing the sub-array ['APPLE',2] because 'apple' was conatined in the array at that index) ?

Thanks - I really appreciate the help from here.

like image 291
Reno Avatar asked Feb 05 '11 02:02

Reno


3 Answers

You can use Array.select to filter out items:

>> 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 items from the, for which the given block (here a != "APPLE") returns true.

like image 113
miku Avatar answered Sep 16 '22 13:09

miku


I tested this, it works:

my_array.delete_if { |x| x[0] == 'APPLE' }
like image 32
Girish Rao Avatar answered Sep 16 '22 13:09

Girish Rao


my_array.reject { |x| x[0] == 'APPLE' }
like image 33
DigitalRoss Avatar answered Sep 20 '22 13:09

DigitalRoss