5

I have an array

result = [{:cluster=>[0, 4], :id=>1, :units=>346, :num1=>0.161930681e7, :num2=>0.14223512616e9, "description"=>"Foo"}, { ...

And I want to take out any objects with number of units equal to 0. Looking for something similar to array.splice() but for Ruby What is the best way to do this ?

2 Answers 2

6

You can use the #reject method to return the array without objects whose :units equals 0:

result.reject { |hash| hash[:units] == 0 }

There's also #reject! and #delete_if, which can be used in the same way as above but both modify the array in place.

Hope this helps!

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

Comments

1

You can achieve the same result using select method implemented on the Array class:

result.select { |el| el[:units] == 0 }

2 Comments

This seems to be how to create a new array with the objects with units = 0
Ah, I see what you wanted. You wanted to get rid of the objects with units == 0, not an array of those objects.You are right.

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.