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,开发者_JAVA技巧 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
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
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.
You should try any?
plays.any? { |play| play.score > mi.score }
精彩评论