Mohamed Omezzine
Mohamed Omezzine

Reputation: 1104

remove elements from array in ruby

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?

Upvotes: 0

Views: 202

Answers (4)

morri
morri

Reputation: 196

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

Upvotes: 0

sawa
sawa

Reputation: 168081

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

Upvotes: 4

toxicate20
toxicate20

Reputation: 5410

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"]

Upvotes: 0

Hck
Hck

Reputation: 9167

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).

Upvotes: 3

Related Questions