0

I would like to select from an array the four highest elements in descending order in terms of length.

I sorted the array in descending order, and picked the elements.

Is there a more elegant way to do this?

4
  • 2
    arr.max_by(n) {|i| #condition } in certain cases will work. Commented Jul 4, 2017 at 22:11
  • If you want to collect the first n objects that satisfy a condition then maybe use each_with_object or with_object with an array object and build it up until you collect n objects. Commented Jul 4, 2017 at 22:16
  • The thing: I want elements that are highest among all the other elements, not the ones that meet a specific condition. Would you please provide an example of how to accomplish it using each_with_object or with_object? Commented Jul 5, 2017 at 1:07
  • Then I would not recommend each_with_object or with_object. On another note be aware of behaviour when using max_by with duplicate elements i.e. [9,9,8].max_by(2, &:itself) #=> [9, 9]. And also note there is the corresponding min_by method too. Commented Jul 5, 2017 at 3:06

1 Answer 1

3
%w(one two three four five size seven eight).max_by(3, &:length)
=> ["seven", "eight", "three"]
Sign up to request clarification or add additional context in comments.

2 Comments

My bad. I have re-phrased my question.
max_by(3, &:length) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.