Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a multi-dimensional array of this form:

array = [["http://domain.com/product.html", 10], ["http://domain.com/product.html", 150], ["http://domain.com/product.html", 500]]

I need to delete all arrays that have the last value smaller than 150.

I already tried the following, but it doesn't seem to have any effect:

array.delete_if {|element| element.last < 150 }

Any help will be highly appreciated. Thanks.

share|improve this question
4  
Your one should work.. What output you got ? –  Arup Rakshit Apr 3 at 9:45
    
It somehow gives me the same array, it doesn't delete any element from it. –  user3493101 Apr 3 at 9:55
1  
The code you've posted works as expected: codepad.org/CvR9Ykfr –  Stefan Apr 3 at 10:00

2 Answers 2

up vote 1 down vote accepted

I would probably do it this way:

array.reject!{|x| x if x.last < 150}
share|improve this answer
    
This is not an answer to this post,, It is another way to solve this.. Do you know why #delete_if didn't work in OP's example, which I am quite sure should work –  Arup Rakshit Apr 3 at 9:46
2  
Perhaps the OP didn't refer to the return value, but referred to array again. That is the point of this answer. –  sawa Apr 3 at 10:01
1  
@sawa #delete_if destructive... –  Arup Rakshit Apr 3 at 10:02
1  
I don't know why this answers has been entertained, which has not been asked.. OP didn't ask how to do it, while OP asked why not working –  Arup Rakshit Apr 3 at 10:03
1  
@user3493101 Although this answer misleading, correct way to write is array.reject!{|x| x.last < 150}. If you like it, teach yourself, this way. –  Arup Rakshit Apr 3 at 10:06

You can also use this:

array.map{|f| f if f.last < 150}.compact

I don't know if it is better or not than Akarsh, just another solution that I would have used. Anyways, your solution works, user3493101, but if it doesn't, you can still use that.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.