Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何根据ID列表对对象数组重新排序_Ruby_Arrays_Ruby On Rails 3_Sorting - Fatal编程技术网

Ruby 如何根据ID列表对对象数组重新排序

Ruby 如何根据ID列表对对象数组重新排序,ruby,arrays,ruby-on-rails-3,sorting,Ruby,Arrays,Ruby On Rails 3,Sorting,我有一个对象任务,如下所示: class Task include HTTParty attr_accessor :id, :name, :assignee_status, :order def initialize(id, name, assignee_status) self.id = id self.name = name self.status = status self.order = order end end 因此,当我加载任务列

我有一个对象任务,如下所示:

class Task
  include HTTParty

  attr_accessor :id, :name, :assignee_status, :order

  def initialize(id, name, assignee_status)
    self.id = id
    self.name = name
    self.status = status
    self.order = order
 end
end
因此,当我加载任务列表时,我会给它们一个特定的顺序,如下所示:

i = 0
@tasks.each do |at|
    at.order = i
    i += 100
end    
然后,该列表通过json发送到客户端应用程序,该客户端应用程序向用户显示is,并允许拖放。某些任务重新排序后,前端应用程序会将一个列表发送回服务器,其中包含新顺序中的所有任务ID

例如: 23,45,74,22,11,98,23

我想做的是根据我找到的ID对对象数组重新排序。我想做的是将所有顺序设置为0,然后在矩阵上单独搜索每个对象,并相应地设置它们的优先级。但这感觉不对。。。感觉像是计算密集型的

有没有一种聪明的方法可以做到:


ArrayOfTaskObjects.orderbyAttribute(id)??

可能最简单的方法是使用索引迭代参数,例如:

params['task_ids'].split(",").each_with_index do |task_id, idx|
  task = lookup_the_task_based_on_id
  task.order = idx
end
发生了什么:

sort\u by\u id
方法接收一个对象数组-这是您的任务数组

在代码的第一行中,创建了一个散列,它将每个任务id存储为键,将任务对象存储为值

第二行代码根据键对哈希进行排序(请注意,r.sort_by方法返回一个二维数组,例如
[[23,Task],[44,Task],[54,Task]

最后,第三行代码将二维数组展平为一维数组,greps从二维数组中删除所有id,使任务数组保持有序

def sort_by_id(array)

  r = array.inject({}) { |hash, element| hash.merge!(element.id => element) }
  temp_array = r.sort_by {|k,_| k}
  temp_array.flatten!.grep(temp_array.last.class)

end