Suppose that after sorting an array with a custom block you need to get all the elements that have the max value.
A common method would be to use Enumerable#take_while
like this
array = [ 1, 3, 2, 3, 2, 3 ].sort {|a,b| b - a}
array.take_while { |e| e == array[0] }
#=> [3, 3, 3]
Now, when you are beautifully chaining methods and don't want to stop the chain just for storing the sorted array (which you'll need for referencing its first element in the take_while
block), how would you do it?
I posted the question and an answer for reference, but I probably missed better ways, so feel free to post your own method
CodePudding user response:
My own response to the question is to use Enumerable#slice_when
like this
[ 1, 3, 2, 3, 2, 3 ].sort {|a,b| b - a}.slice_when {|a,b| b != a}.first
#=> [3, 3, 3]
note: Performance wise it seems OK since slice_when
returns an Enumerator
.
With ruby >= 2.5, combining @engineersmnky and @Cary methods
[ 1, 3, 2, 3, 2, 3 ].then { |arr| mx = arr.max; arr.select { |elm| elm == mx } }
#=> [3, 3, 3]
CodePudding user response:
You can try this
pry(main)> [ 1, 2, 2, 3, 3, 3 ].sort.slice_when {|a,b| b > a}.to_a.last
=> [3, 3, 3]
A bit similar of the last solution but also different.
Source https://ruby-doc.org/core-3.0.2/Enumerable.html#method-i-slice_when