2

I have an array which contains numbers and alphabets something like:

newArray = ["1 a", "1 b" ,"2 c", "2 a"]

I would like to sort them in a way that the output is expected as follows:

newArray = ["2 a", "2 c" ,"1 a", "1 b"]

What I want to do is sort the numbers in descending order and if the numbers are same, then sort alphabetically

Can I implement a comparison function in sort_by or is there a way to do that using ruby sort

3 Answers 3

7

First you should use a better representation of your input. You can parse your existing array for example like this:

arr = newArray.map { |s| x,y = s.split; [x.to_i, y] }
# => [[1, "a"], [1, "b"], [2, "c"], [2, "a"]]

Then we can sort as we wish using sort_by:

arr.sort_by { |x,y| [-x, y] }
# => [[2, "a"], [2, "c"], [1, "a"], [1, "b"]]
Sign up to request clarification or add additional context in comments.

5 Comments

I am new to ruby. So still learning. Is there a way I can convert the sorted map back to the original array format as I need to maintain the format for other comparison across the code.
@blathia: You can do that using another map and string formatting, for example with String#%. That said, I recomment not using strings to represent a tuple of values. You will lose type safety and handling of the strings will be awkward (as you can see, even for this simple application we need to parse the strings anyway)
Store arr= arr.sort_by { |x,y| [-x, y] } then do arr.map{|a| a=a.join(" ")}
@KirtiThorat: You realize I was intentionally not giving the complete solution? This has some didactical aspect as well :)
@NiklasB. I kinda thought of that but decided to make his life easy. :)
2

Similar to @NiklasB. 's answer above (copied his sort_by)

arr.map(&:split).sort_by { |x,y| [-x.to_i, y] }

=> [["2", "a"], ["2", "c"], ["1", "a"], ["1", "b"]]

1 Comment

This is the more Ruby-ish solution.
0

In a less elegant way, you can do that

    arr.sort! do |p1, p2|
      num1, str1 = p1.split(' ')
      num2, str2 = p2.split(' ')
      if (num1 != num2)
        p2 <=> p1
      else
        p1 <=> p2
      end
    end
    $stdout.puts arr

Comments

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.