Reputation: 3422
I have an array that looks like this
ranking_array = ['NC', '40', '30/5', '30/4', '30/3', '30/2', '30/1', '30', '15/5', '15/4', '15/3', '15/2', '15/1', '15', '5/6', '4/6', '3/6', '2/6', '1/6', '0', '-2/6', '-4/6', '-15', '-30']
I have also a model user, my user has a ranking which is a value that is contained in ranking_array.
I have a model tournament with a max_ranking and a min_ranking which are both values contained in the ranking_array.
A user can only subscribe to a tournament if
tournament.min_ranking<=user.ranking <= tournament.max_ranking
I need a way to compare the value of rankings (ie ranking_array index because ranking_array is sorted from the lowest to highest ranking)
Thus, I need to write down a method comparing these values indexes:
if current_user.ranking_index > tournament.max_ranking_index
flash[:alert] = "Vous n'avez pas le classement requis pour vous inscrire dans ce tournoi"
elsif current_user.ranking_index < tournament.min_ranking_index
flash[:alert] = "Vous n'avez pas le classement requis pour vous inscrire dans ce tournoi"
How can I achieve that with each_with_index ?
Upvotes: 1
Views: 381
Reputation: 104
I think I understand what you're trying to achieve: You want to make sure that a player has a ranking between the minimum and maximum ranking, but you only store the ranking in each model as a string. The ranking array has rankings in ascending order, but I'm not sure if #each_with_index is the way to go. The other answer is cleaner. You could also read about Rails built-in enum class that would make this cleaner and easier to understand when a new or outside developer is reading it.
Your question was about how to do this with each_with_index though, so something like this would be what you want.
ranking_array.each_with_index do |ranking, i|
return i if ranking == current_user.ranking
end
Also, both of your alerts are flashing the same message. If this is intentional and not a typo, you could combine your if statement like this:
if current_user.ranking_index > tournament.max_ranking_index || current_user.ranking_index < tournament.min_ranking_index
flash[:alert] = "Vous n'avez pas le classement requis pour vous inscrire dans ce tournoi"
end
Upvotes: 3
Reputation: 1318
If you want to get the indexes of the rankings, just call .index on the ranking_array.
ranking_array.index(current_user.ranking)
Upvotes: 2