Take the 2-minute tour ×

How can I implement this in Ruby? Is there any one line of code technique? Let's say I want to get rid of all the elements which are less than 3 of an integer array.

share|improve this question
add comment

3 Answers

up vote 17 down vote accepted

You can use either new_array = array.reject {|x| x < 3} (reject returns a new array) or array.reject! {|x| x < 3} (reject! aka delete_if modifies the array in place).

There's also the (somewhat more common) select method, which acts like reject except that you specify the condition to keep elements, not to reject them (i.e. to get rid of the elements less than 3, you'd use new_array = array.select {|x| x >= 3}).

share|improve this answer
Thanks for cool technique ;) –  Chan Feb 15 '11 at 16:19
add comment
share|improve this answer
Thanks ;) –  Chan Feb 15 '11 at 16:19
add comment

Probably worth pointing out that

array.reject! {|x| x < 3}


array.delete_if {|x| x < 3}

Are the same, but

array.reject {|x| x < 3}

Will still return the same result, but not change the "array".

share|improve this answer
add comment

Your Answer


