Home » Featured, How-to, Ruby

Ruby: Sorting an array based on other array values

18 February 2013 No Comment

In the following article I will try to show you, the power of Ruby in three short hash/array examples.
First I will show you how to sort a key value array by value. Second I will modify the keys name and create another array with this keys (which are already sorted by values).
Third we will sort an array based on the other array keys.

1. For example we have:

y = {"x"=>990,"y"=>2,"z"=>666,"a"=>222,"b"=>1}

To sort them based on the value is easy:

y.sort_by {|name,weight| weight}
=> [["b", 1], ["y", 2], ["a", 222], ["z", 666], ["x", 990]]

2. Now we want to return just the keys and simultaneously modify them:

y = y.sort_by{|name,weight| weight}.map{|name,_| name.gsub('x','xx')}
=> ["b", "y", "a", "z", "xx"]

So everything is done just in 1 line of code … For me is pretty pretty amazing 🙂

3. Now we have another hash/mash and we want to order it’s values by the data from the above array.
So we have something like:

x = {"xx"=>{"i"=>1,"j"=>2},"z"=>{"i"=>2,"j"=>3},"a"=>{"u"=>555}}

and we want to sort them based on the y order of keys.

 x.sort_by{|name,definition| y.index(name)}
=> [["a", {"u"=>555}], ["z", {"i"=>2, "j"=>3}], ["xx", {"i"=>1, "j"=>2}]]

So we did 3 (or 4?) things with 2 lines of code: sorting an hash, modify it’s keys and create a new array, sorted another hash based on other array keys.

I’m still a beginner in Ruby, but it was love at first sight.

BlinkList Diigo Digg Facebook Furl Google Mister Wong Newsvine Reddit StumbleUpon Simpy Technorati Yahoo DZone

Hide Bookmarks

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.