0

I have an array and I want to remove some elements. I tried this but it doesn't work:

@restaurants.each_with_index do |restaurant, i|

if (restaurant.stars > 3)  @restaurants.slice!(i)     end

end

How can I do it?

1
  • 2
    You will find the answer below from Hck. But you could have found that easily by looking at the documentation first. Commented Nov 15, 2012 at 11:40

4 Answers 4

4
@restaurants.reject!{|restaurant| restaurant.stars > 3}
Sign up to request clarification or add additional context in comments.

Comments

3

You can use Array#delete_at(index): see rubydoc

But the best way for you will be to use reject! (rubydoc) or delete_if (rubydoc).

Comments

0

If restaurants is an array you can use pop, e.g.

a = [ "a", "b", "c", "d" ]
a.pop     #=> "d"
a.pop(2)  #=> ["b", "c"]
a         #=> ["a"]

Comments

0
@restaurants.reject! {|restaurant| restaurant.stars > 3}

Comments

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.