5

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.

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

Tho I think The MYYN's deconstructing yield (I think that's what it's called) is nice.
A variation of this: a.reject { |x, y| x == 'APPLE' }
Girish Rao, that's fine, good point. I suppose, for practice, I could argue that reject will work for any Enumerable and not just Array, but that argument could cut both ways: since delete_if is implemented only for Array you can probably count on it running quickly.
You'll find reject and its counterpart select used a lot more than delete_if. I think it's because they're more generic, used more often, and easier to remember as a result.
4

I tested this, it works:

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

1 Comment

Using delete_if seems really human readable to me. I love this place - 3 almost instant answers all different and all of them work. I learned a lot - thanks all!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.