user4584963 user4584963 - 3 months ago 9
Ruby Question

Ruby on rails How to find first item in array that matches items in another array

I have a leaderboard array that looks something like this:

[{:member=>"1", :score=>7.0, :rank=>1}, {:member=>"5", :score=>6.0, :rank=>2}, {:member=>"4", :score=>5.0, :rank=>3}, {:member=>"3", :score=>4.0, :rank=>4}, {:member=>"2", :score=>3.0, :rank=>5}]


I also have an array of active user ids
[3,5]
.

How can I get the member number of the highest ranked active user and assign that to a variable? The leaderboard array will always be in order of rank.

Answer

One method would be to reduce your array to only entries who's :member is also in the active user IDs array, and then take the first element of that array:

leaderboard = [...]
active_user_ids = [3,5]

leaderboard.take_while{ |m| active_user_ids.include?(m[:member].to_i) }.first
Comments