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:
开发者_StackOverflow中文版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.
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
.
my_array.reject { |x| x[0] == 'APPLE' }
I tested this, it works:
my_array.delete_if { |x| x[0] == 'APPLE' }
精彩评论