# Sort array by two attributes? (like sql "order by A, B")

**URL:** <https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566>\
**Category:** Ruby\
**Created:** [August 11, 2008, 5:18pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566 "2008-08-11T17:18:42Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 11, 2008, 5:18pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/1 "2008-08-11T17:18:42Z")

</div>

IN sql we can pass two arguments to the ‘order by’ component, and it  
will order the results by A, and then B in the cases where A is the  
same.

Can anyone think of a way to do the same thing with a ruby array? For  
example, if the array holds objects that have attributes/methods  
“lastname” & “firstname”, to order the objects in a similar way to the  
sql query?

thanks  
max

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 11, 2008, 5:30pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/2 "2008-08-11T17:30:10Z")

</div>

> Can anyone think of a way to do the same thing with a ruby array? For  
> example, if the array holds objects that have attributes/methods  
> “lastname” & “firstname”, to order the objects in a similar way to the  
> sql query?

Just use Enumerable#sort:  
[http://ruby-doc.org/core/classes/Enumerable.html#M003150](http://ruby-doc.org/core/classes/Enumerable.html#M003150)

objects.sort do |a,b|  
comp = (a.lastname \<=\> b.lastname)  
comp.zero? ? (a.firstname \<=\> b.firstname) : comp  
end

James

> **[The If Works – The If Works](https://blog.jcoglan.com/)**

> **[jcoglan - Overview](https://github.com/jcoglan)**
>
> jcoglan has 145 repositories available. Follow their code on GitHub.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 11, 2008, 5:30pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/3 "2008-08-11T17:30:46Z")

</div>

On Mon, Aug 11, 2008 at 5:16 PM, Max W.  
[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> IN sql we can pass two arguments to the ‘order by’ component, and it  
> will order the results by A, and then B in the cases where A is the  
> same.
> 
> Can anyone think of a way to do the same thing with a ruby array? For  
> example, if the array holds objects that have attributes/methods  
> “lastname” & “firstname”, to order the objects in a similar way to the  
> sql query?

Here’s one way: the trick is to create an array with the fields you want  
to order by in the sort\_by block:

irb(main):001:0\> class A  
irb(main):002:1\> attr\_accessor :a,:b  
irb(main):003:1\> def initialize a,b  
irb(main):004:2\> @a = a  
irb(main):005:2\> @b = b  
irb(main):006:2\> end  
irb(main):007:1\> end  
=\> nil  
irb(main):008:0\> ary = [A.new(1,2), A.new(1,3), A.new(1,1),  
A.new(2,3), A.new(2,1)]  
=\> [#\<A:0xb7b68890 @b=2, @a=1\>, #\<A:0xb7b6887c @b=3, @a=1\>,  
#\<A:0xb7b68868 @b=1, @a=1\>, #\<A:0xb7b68854 @b=3, @a=2\>, #\<A:0xb7b68840  
@b=1, @a=2\>]  
irb(main):009:0\> ary.sort\_by {|x| [x.a,x.b]}  
=\> [#\<A:0xb7b68868 @b=1, @a=1\>, #\<A:0xb7b68890 @b=2, @a=1\>,  
#\<A:0xb7b6887c @b=3, @a=1\>, #\<A:0xb7b68840 @b=1, @a=2\>, #\<A:0xb7b68854  
@b=3, @a=2\>]

Hope this helps,

Jesus.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 11, 2008, 5:34pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/4 "2008-08-11T17:34:57Z")

</div>

JesÃºs Gabriel y GalÃ¡n wrote:

> Here’s one way: the trick is to create an array with the fields you want  
> to order by in the sort\_by block:  
> Hope this helps,
> 
> Jesus.

That’s a neat trick, thanks! I actually like the first one better  
though as you can swap a & b around in each test to get (eg) sorted by  
name ascending and then a date field descending.

Thanks a lot guys!  
max

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 11, 2008, 5:51pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/5 "2008-08-11T17:51:15Z")

</div>

> That’s a neat trick, thanks! I actually like the first one better  
> though as you can swap a & b around in each test to get (eg) sorted by  
> name ascending and then a date field descending.

Just use -x.b:

a.sort\_by{|x| [x.name, -x.date]}

Sort\_by is much faster than sort with a block.

gegroet,  
Erik V.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 11, 2008, 6:00pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/6 "2008-08-11T18:00:04Z")

</div>

> Sort\_by is much faster than sort with a block.

This is often true as sort\_by only calls methods on each object once,  
but it  
is not universally true – see  
[http://ruby-doc.org/core/classes/Enumerable.html#M003151](http://ruby-doc.org/core/classes/Enumerable.html#M003151) for more  
information, and run some benchmarks for your use case if it’s a big  
issue.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 11, 2008, 7:40pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/7 "2008-08-11T19:40:18Z")

</div>

On Mon, Aug 11, 2008 at 8:48 AM, Erik V. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> > That’s a neat trick, thanks! I actually like the first one better  
> > though as you can swap a & b around in each test to get (eg) sorted by  
> > name ascending and then a date field descending.
> 
> Just use -x.b:
> 
> a.sort\_by{|x| [x.name, -x.date]}

Doesn’t always work. I keep this handy:

class RevCmp  
attr\_reader :this

```
def initialize(obj)
  @this = obj
end

def <=>(other)
  other.this <=> @this
end

# not delegating anything else because this is explicitly a 

```

throwaway  
# object used only inside a sort\_by block  
end

and then you have

a.sort\_by {|x| [x.name, RevCmp.new(x.date)]}

you could even use a top-level method so you can say

a.sort\_by {|x| [x.name, descending(x.date)]}

where descending(x) returns RevCmp.new(x)

You could even mix it into object to get

a.sort\_by {|x| [x.name, x.date._descending_]}

where I use the underscores as a cosmetic way of making it stand out  
inside the sort block

martin

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 11, 2008, 8:38pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/8 "2008-08-11T20:38:22Z")

</div>

2008/8/11 James C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> objects.sort do |a,b|  
> comp = (a.lastname \<=\> b.lastname)  
> comp.zero? ? (a.firstname \<=\> b.firstname) : comp  
> end

For this usecase there’s also Numeric#nonzero?

objects.sort do |a, b|  
(a.lastname \<=\> b.lastname).nonzero? ||  
(a.firstname \<=\> b.firstname)  
end

Regards,  
Pit

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [February 18, 2013, 6:42pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/9 "2013-02-18T18:42:33Z")

</div>

I would just create an array containing the parts you want to compare:

objects.sort { |a,b| [a.lastname, a.firstname] \<=\> [b.lastname, b.firstname] }

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 12, 2008, 10:22am UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/10 "2008-08-12T10:22:04Z")

</div>

Pit C. wrote:

> objects.sort do |a, b|  
> (a.lastname \<=\> b.lastname).nonzero? ||  
> (a.firstname \<=\> b.firstname)  
> end

Wow, this is all great stuff. thanks folks.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [February 18, 2013, 11:02pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/11 "2013-02-18T23:02:07Z")

</div>

On Mon, Feb 18, 2013 at 6:42 PM, Jack V. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I would just create an array containing the parts you want to compare:
> 
> objects.sort { |a,b| [a.lastname, a.firstname] \<=\> [b.lastname,  
> b.firstname] }

In theory this is less efficient since there are two Array instances  
created per comparison. If you go for the Array solution, using  
#sort\_by is probably better:

objects.sort\_by {|a| [a.lastname, a.firstname]}

Kind regards

robert

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 13, 2014, 2:05pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/12 "2014-08-13T14:05:05Z")

</div>

Can someone explain to me why it works?

array.sort\_by{|x| [x.name, -x.date] }

Why does this kind of sorting work on an Array input?

How would I know that it first starts by the first  
Array member, and then the second? Why is it not  
the other way (from last to first, rather from first  
to last entry)?

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 13, 2014, 6:28pm UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/13 "2014-08-13T18:28:03Z")

</div>

Robert H. wrote in post #1155030:

> Can someone explain to me why it works?
> 
> array.sort\_by{|x| [x.name, -x.date] }
> 
> Why does this kind of sorting work on an Array input?

When an Array calls a method, the block specified after  
the method call does not have to take an array as  
an argument. Here is an example:

class Array  
def do\_stuff

```
if block_given?
  map do |array_elmt|
    yield array_elmt
  end
else
  self
end

```

end  
end

data = [10, 20, 30]

y = data.do\_stuff { |x| x\*2 }  
p y

y = data.do\_stuff  
p y

–output:–  
[20, 40, 60]  
[10, 20, 30]

Enumerable#sort\_by() uses a block in a similar fashion.  
sort\_by() sends each  
element of an Array that you want to sort to the block to create a new  
value that it will use  
as a stand in for the original value when sorting. The return values  
from the block are what sort\_by() uses as the values to sort. For  
example, look at this Hash:

mapped\_orig\_vals = {

```
['David', 2] => objA
['David', 1] => objB,

```

}

After creating each entry in the hash, sort\_by() sorts the keys, which  
are arrays, to produce:

ordered\_keys = [

[‘David’, 1],  
[‘David’, 2],

]

After sorting the keys, sort\_by() looks up the value  
associated with each key to get the original value, e.g.

ordered\_orig\_vals = ordered\_keys.map do |key|  
mapped\_orig\_values[key]  
end  
#=\>[objB, objA]

> How would I know that it first starts by the first  
> Array member, and then the second?

If by Array you mean the Array returned by the sort\_by() block, you  
would know by reading about how ruby determines whether two  
arrays are equal or not:

> **[Class: Array (Ruby 2.1.2)](http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-3C-3D-3E)**
>
> Comparison — Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other\_ary. | Class : Array - Ruby 2.1.2

In every computer programming language I’ve studied, things like Arrays  
and Strings are always compared by starting with the first  
element/character, and if they are the same, then the second element is  
compared, etc. Once a difference is found, then one Array/String is  
considered smaller than the other Array/String. If all the elements are  
the same but one Array/String is shorter than the other, the shorter one  
is considered smaller. If all the elements are the same, and they are  
the same length, then they are considered equal.

On the other hand, if by Array you mean the original Array you are  
trying to sort, it is irrelevant which end of the array you start at.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [August 15, 2014, 11:36am UTC](https://www.ruby-forum.com/t/sort-array-by-two-attributes-like-sql-order-by-a-b/145566/14 "2014-08-15T11:36:17Z")

</div>

Just use Enumerable#sort: [http://www.ruby-doc.org](http://www.ruby-doc.org)  
and you know this video [http://youtu.be/1DzlYY4saMY](http://youtu.be/1DzlYY4saMY)
