Reno
Reno

Reputation: 2982

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

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.

Upvotes: 5

Views: 2287

Answers (3)

Girish Rao
Girish Rao

Reputation: 2669

I tested this, it works:

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

Upvotes: 4

DigitalRoss
DigitalRoss

Reputation: 146053

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

Upvotes: 6

miku
miku

Reputation: 188004

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.

Upvotes: 7

Related Questions