user3442206
user3442206

Reputation: 587

How to sort a 2 dimentional array in ruby

I know this may be answered a million times, but i can't quite find what i wanna do in my case.

I have an array as following:

tag_array = [[tag1, tag_count1], [tag1, tag_count2], [tag3, tag_count3], [tag4, tag_count4]]

And i want to sort it alphabetically according to tag1, tag2, tag3...

I have tried the following:

tag_array.sort {|a,b| a[0] <=> b[0]}

but without luck !

Am i missing something here ?

Thanks!

PS: tag1, tag2, tag3... are strings.

Upvotes: 0

Views: 67

Answers (4)

Moin Haidar
Moin Haidar

Reputation: 1694

2.2.0 :007 > tag_array = [['tag1', 3], ['tag2', 2], ['tag3', 23], ['tag4', 44]]
 => [["tag1", 3], ["tag2", 2], ["tag3", 23], ["tag4", 44]] 
2.2.0 :008 > tag_array.sort_by{|tag| [tag[1], tag[0]]}
 => [["tag2", 2], ["tag1", 3], ["tag3", 23], ["tag4", 44]] 
2.2.0 :009 > tag_array.sort_by{|tag| [tag[0], tag[1]]}
 => [["tag1", 3], ["tag2", 2], ["tag3", 23], ["tag4", 44]] 

Upvotes: 0

Chris Arcand
Chris Arcand

Reputation: 30

You can just use tag_array.sort

You don't need to worry about adding your own block, assuming you're just doing [String, Integer] array pairs within an array (which you are). Sort handles that for you as arrays are compared in an element-wise manner (thanks mudasobwa for this added clarity).

Upvotes: 1

Shadi Mahasneh
Shadi Mahasneh

Reputation: 175

If u say

arr2 = arr.sort {|a,b| a[0] <=> b[0]}

or

arr2 = arr.sort_by{|x,y|x}

it works just fine

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Enumerable#sort_by comes to the rescue:

tag_array.sort_by { |el| el.first }

The above might be written in short notation (credits to @justin-licata):

tag_array.sort_by &:first

BTW, sort_by is proven to be much more efficient that sort.

Upvotes: 5

Related Questions