Noob ?: sorting hashes within an array by another array

I have two arrays:

@new_array_ids = params[@resource_key].map { |k| k.to_i }

@new_array_us = ProjectAssignment.find(@new_array_ids)

Let’s say:

@new_array_ids ----> [5,3]

@new_array ---->
[#<ProjectAssignment:0x4706cd8 @attributes={“id”=>“3”,
“resource_id”=>“1”}>, #<ProjectAssignment:0x4706c4c
@attributes={“id”=>“5”,“resource_id”=>“4”}>]

I want the hashes in @new_array to be sorted by @new_array_ids. At first
I thought I would just be able to use :order => @new_array_ids, or
something like that in the find. But the :order option only takes SQL
fragments (?). So in order to get something like:

@new_array_sorted ---->
[#<ProjectAssignment:0x4706c4c
@attributes={“id”=>“5”,“resource_id”=>“4”}>,
#<ProjectAssignment:0x4706cd8 @attributes={“id”=>“3”,
“resource_id”=>“1”}>]

I need to identify the position of each element in @new_array_ids, find
each of the attributes whose id matches a value in @new_array_ids, sort
by the order of values in @new_array_ids.

I new to ruby + rails, so please let me know if there’s a really simple
way of doing this. Thanks.

Thanks a lot! That’s really great! Also, thanks for letting me know
about Symbol#to_proc; it’s really concise.

@new_array_us = ProjectAssignment.find(@new_array_ids).
sort_by {|pa| @new_array_ids.index(pa.id)}

You can even simplify that bit using Symbol#to_proc

@new_array_ids = params[@resource_key].map(&:to_i)

On Jun 25, 2007, at 4:09 PM, Patrick Berkeley wrote:

@new_array ---->
@new_array_sorted ---->

I new to ruby + rails, so please let me know if there’s a really
simple
way of doing this. Thanks.

Well, it’s really not too bad.

@new_array_us = ProjectAssignment.find(@new_array_ids).
sort_by {|pa| @new_array_ids.index(pa.id)}

(which I’d have put on a single line if it weren’t for the inevitable
line-wrapping in the email)

In fact, if you didn’t want to sort the results, you could have
skipped the mapping .to_i since ActiveRecord will treat .find(“3”)
and .find(3) the same.

You can even simplify that bit using Symbol#to_proc

@new_array_ids = params[@resource_key].map(&:to_i)

Enjoy!

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs