0

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!

2 Answers 2

1

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.

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

2 Comments

I have an array of bikes that I want to return only if those bikes can be checked out. The array however is returning bikes that should not be showing up. Does that make more sense?
@TallPaul so you just need to invert the delete condition. or invert the where clause, that is more complex.
1

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.

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.