Noob
Noob

Reputation: 119

Sorting Pair with second value in Ruby

I want to sort the list according to second value of a pair, this is my code for class Pair and make_pair :

    class Pair

      attr_accessor :first,:second

    end

    def make_pair(x,y)
      temp = Pair.new

      temp.first = x
      temp.second = y

      return temp
    end

    arr = []

    arr.push(make_pair("abc",make_pair("def",2)))
    arr.push(make_pair("abc",make_pair("def",3)))
    arr.push(make_pair("abc",make_pair("def",1)))
    arr.push(make_pair("abc",make_pair("def",4)))

    arr.sort {|a,b| a.second.second <=> b.second.second}

    print(arr[0].second.second)

I saw this Sorting a two-dimensional array by second value and tried but list remains the same, how to correctly do it? I want to sort it by arr.second.second i.e the integer value.

Upvotes: 1

Views: 597

Answers (2)

Ashik Salman
Ashik Salman

Reputation: 1879

You can easily perform this task as:

arr.sort_by! { |x| x.second.second }

If you don't want to change the original array, remove the ! from method signature and save the result to another variable:

new_arr = arr.sort_by { |x| x.second.second }

Upvotes: 0

Igor Pantović
Igor Pantović

Reputation: 9246

Method #sort does not modify the original array. It returns a new one with elements sorted: https://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-sort

You just need to assign sorted result to a variable:

arr = arr.sort {|a,b| a.second.second <=> b.second.second}

Style comments

That said, even though it's not asked in the question, you could make this code cleaner by removing make_pair method and putting it's contents into Pair#initialize:

class Pair
  attr_reader :first, :second

  def initialize(first, second)
    @first = first
    @second = second
  end
end

I feel like sort is unnecessarily verbose for this scenario and #sort_by would fit better:

sorted = arr.sort_by{ |item| item.second.second }

Upvotes: 3

Related Questions