Ruby on Rails Friday, May 29, 2015

On 2015-May-29, at 09:24 , Gm <javaplayer@gmail.com> wrote:

> Hi, I have this hash:
>
> hash = { 4049=>[4133, 100], 5814=>[4075, 84], 382543=>[4064, 74], 382544=>[4065, 99], 382545=>[4066, 75] }
>
> I need to sort (DESC) this hash by the second item of array.
> Example: 100, 84, 74, 99, 75
>
> How can I solve this problem ? I'm using sort method but can't work it out.
>
> Thanks.

Well, assuming that you know a Hash isn't really sortable and you'll end up with an Array (of Arrays)...

irb2.2.2> hash = { 4049=>[4133, 100], 5814=>[4075, 84], 382543=>[4064, 74], 382544=>[4065, 99], 382545=>[4066, 75] }
#2.2.2 => {4049=>[4133, 100], 5814=>[4075, 84], 382543=>[4064, 74], 382544=>[4065, 99], 382545=>[4066, 75]}
irb2.2.2> hash.sort_by {|k,v| v[1]}
#2.2.2 => [[382543, [4064, 74]], [382545, [4066, 75]], [5814, [4075, 84]], [382544, [4065, 99]], [4049, [4133, 100]]]
irb2.2.2> hash.sort_by {|k,v| v[1]}.reverse
#2.2.2 => [[4049, [4133, 100]], [382544, [4065, 99]], [5814, [4075, 84]], [382545, [4066, 75]], [382543, [4064, 74]]]
irb2.2.2> hash.sort_by {|k,v| -v[1]}
#2.2.2 => [[4049, [4133, 100]], [382544, [4065, 99]], [5814, [4075, 84]], [382545, [4066, 75]], [382543, [4064, 74]]]


You really want Hash#sort_by

-Rob

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/97435771-D2FE-432F-8B65-371DF693B404%40agileconsultingllc.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment