DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Reorder Arrays, ActiveRecord Collections

12.24.2008
| 6577 views |
  • submit to reddit
        If you need some screwey order for an array this a quick mixin to pull it off.  It'll reorder ActiveRecord collections/arrays as well.  Just put this in your Environment.rb file or put it in lib/array_mixins.rb and do a "require 'array_mixins'" in your Environment.rb

class Array

  #reorders an array
  #
  # simple example
  #   arr1 = [0,1,2,3,4]
  #   arr2 = [3,2,4,1, 0]
  #   arr1.reorder(arr2) = [3,2,4,1,0]
  #
  # active record example
  # idarr = [4,2,10,8]
  # users = User.find(idarr)
  # users.reorder(idarr, "id").collect {|u| u.id} = [4,2,10,8]
  #
  # obj_key needs to return a int
  def reorder(array_of_ordered_values, obj_key = "")
    if obj_key.blank? #just collect by position
      return array_of_ordered_values.collect {|a| self[a]}
    else
      h = {}
      self.each do |obj|
        h[obj.send(obj_key)] = obj
      end
      return array_of_ordered_values.collect {|a| h[a]}
    end
  end

end