Question

I am retrieving 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, retrieve only the first five unique elements from the array. Can someone recommend me an efficient way to write a helper for this?

EDIT: So based on the answer provided by squiguy this what I did:

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

That solves most of my problem. But when I am displaying those results I need them back to the original format.

For example the result could be grisHam, aNdy etc.
Was it helpful?

Solution

My venture would be something like:

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

If you are using the union operator for two arrays, there is no need for uniq.

(a1 | a2).sort.take(5)

OTHER TIPS

to get the sorted unique array:

member_results.sort.uniq

to loop 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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top