Ruby sort array alphabetically, unique and loop at least 5 times

I am extracting elements from an array:

- member_results.each do |member| = member 

It returns something like this:

 ["John", "Jason", "Andy", "Zee", "Sandy", "Randy", "Grisham"] 

I need to sort the array alphabetically, get only the first five unique elements from the array. Can someone recommend me an efficient way to write an assistant for this?

EDIT: Therefore, based on the answer received by squiguy, this is what I did:

 member_results.map(&:downcase).sort.uniq.take(5) 

This solves most of my problem. But when I show these results, I need them back in the original format.

 For example the result could be grisHam, aNdy etc. 
+4
source share
2 answers

My enterprise would be something like:

 member_results.sort_by(&:downcase).uniq.take(5) 

If you use the join operator for two arrays, there is no need for uniq .

 (a1 | a2).sort.take(5) 
+4
source

to get a sorted unique array:

 member_results.sort.uniq 

to iterate over the first 5 unique members:

 member_results.sort.uniq[0..4].each do |m| ... end 

or

 member_results.sort.uniq.first(5).each do |m| ... end 

or

 member_results.sort.uniq.take(5).each do |m| ... end 

 (result1 | result2).sort.uniq.first(5) 
+1
source

Source: https://habr.com/ru/post/1481059/


All Articles