brendan
brendan

Reputation: 29996

Return a value from a loop in Ruby on Rails

I have a game in RoR. The game breaks down like this. There are Levels, Levels have Missions and Missions have Gameplays (your attempt to complete the mission).

To pass a level you just need to complete 1 mission. So in my Level model, I am trying to write method to determine if a user has passed the level and can't seem to get it. I need to return true if the gamplay score is > the score required to pass the mission.

This is where I'm at. How can I exit the loop and return true if I find a Gameplay with a score > the mission score?

  def user_has_passed(user)
    self.missions.each do |mi|
      plays = Gameplay.where(:user_id => user.id, :mission_id => mi.id)
      #code here, if a play.score > mi.score return true, else return false
    end
  end

Upvotes: 2

Views: 4793

Answers (3)

KC S
KC S

Reputation: 4935

You should try any?

plays.any? { |play| play.score > mi.score }

Upvotes: 2

Dutow
Dutow

Reputation: 5668

Why don't you add one more part to the where call?

  good_plays = Gameplay.where(:user_id => user.id, :mission_id => mi.id).where("score > ?", mi.score)

And with this if you get any plays (good.plays.size > 0) you are good

Or with your query, you need one more loop

  plays.each do |play|
    return true if play.score > mi.score
  end

Upvotes: 3

Steve Ross
Steve Ross

Reputation: 4144

return play.score > mi.score

That should handle it succinctly. More verbosely:

return play.score > mi.score ? true : false

or

if play.score > mi.score
  return true
else
  return false
end

Note that the return is not strictly necessary as the last expression evaluated is what your method returns, but it helps to be explicit -- at least at first.

Upvotes: 2

Related Questions