Tall Paul
Tall Paul

Reputation: 2450

Ruby array not deleting all of the correct array elements

A website I have been developing for a bike share program is returning funky results and I am not sure what is wrong with this one function. I am trying to return all of the bikes that are available to be checked out.

def can_checked_out
  bikes = Bike.order(:bike_id).all
  bikes.each do |bike|
    bikes.delete bike if bike.need_repair or bike.addtional_repair_need or bike.checked_out or !bike.passed_inspection
  end
  bikes
end

So it gets all of the bikes, orders them by their id number and iterates through each one to see if it should remove it from the array that it returns. If the bike nees to be repaired/more repair/is checked out or has not been inspected then it should be deleting the bike. Currently I am using 20 bikes and for some reason the even numbers are showing up saying they are there when all of the bikes are checked out.

Any help would be appreciated!

Upvotes: 0

Views: 59

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

Use delete_if:

Deletes every element of self for which block evaluates to true.

The array is changed instantly every time the block is called, not after the iteration is over.

bikes.delete_if { |bike| bike.need_repair || bike.addtional_repair_need || bike.checked_out || !bike.passed_inspection }

The way you're doing it, the problem is that you're iterating over the container you're deleting from, which confuses Ruby.

Upvotes: 1

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

If the checked methods are really db columns, you can use selector in a query:

Bike.order(:bike_id).where(need_repair: false, addtional_repair_need: false, checked_out: false, passed_inspection: true)

But could you explain more cleanly you problem.

Upvotes: 1

Related Questions