有条件地排序字符串数组

时间:2012-10-10 08:10:51

标签: ruby arrays sorting

我有一个数组

[['Part', 'create'], ['Part', 'update'], ['Part', 'delete'], ['Part', 'release'], ['Plan', 'create'], ['Plan', 'update'], ['Plan', 'delete'], ['Plan', 'release'], ['Inspection', 'create'], ['Inspection', 'update'], ['Inspection', 'delete'], ['Inspection', 'release'], ['User', 'create'],['User', 'update']]

我希望按零件,计划,检验创建,更新,删除,发布

的顺序对其进行排序

我希望它按上述顺序排序的原因是

Part 
  has_many plans
Plan 
  belongs_to :part
  has_many inspections
Inspection
  belongs_to :plan

我使用cancan实现了动态角色和权限。需要为用户分配操作(创建,更新,删除,释放)的权限以及显示的顺序  SubjectClass(部分,计划,检查,用户)必须与他们的关系一致。

当我使用排序时,我得到了

a.sort
 => [["Inspection", "create"], ["Inspection", "delete"], ["Inspection", "release"], ["Inspection", "update"], ["Part", "create"], ["Part", "delete"], ["Part", "release"], ["Part", "update"], ["Plan", "create"], ["Plan", "delete"], ["Plan", "release"], ["Plan", "update"], ["User", "create"], ["User", "update"]] 

a.sort_by{|x, y| x[0] <=> y[0]}
=> [["Part", "create"], ["Part", "update"], ["Part", "delete"], ["Part", "release"], ["Plan", "create"], ["Plan", "update"], ["Plan", "delete"], ["Plan", "release"], ["Inspection", "create"], ["Inspection", "update"], ["Inspection", "delete"], ["Inspection", "release"], ["User", "create"], ["User", "update"]] 

可以使用索引方法吗? 稍后可能会添加新的主题类和操作。因此排序顺序可能会发生变化。

2 个答案:

答案 0 :(得分:3)

a = [['Part', 'create'], ['Part', 'update'], ['Part', 'delete'], ['Part', 'release'], ['Plan', 'create'], ['Plan', 'update'], ['Plan', 'delete'], ['Plan', 'release'], ['Inspection', 'create'], ['Inspection', 'update'], ['Inspection', 'delete'], ['Inspection', 'release'], ['User', 'create'],['User', 'update']]
order = [%w{Part Plan Inspection}, %w{create update delete release}]

如果我们假设所有未指定的元素的权重为999(例如示例中为User),则会按给定的顺序对输入数组进行排序:

a.sort_by{|e| e.zip(order).map{|i,j| j.index(i) || 999}}
=> [["Part", "create"],
 ["Part", "update"],
 ["Part", "delete"],
 ["Part", "release"],
 ["Plan", "create"],
 ["Plan", "update"],
 ["Plan", "delete"],
 ["Plan", "release"],
 ["Inspection", "create"],
 ["Inspection", "update"],
 ["Inspection", "delete"],
 ["Inspection", "release"],
 ["User", "create"],
 ["User", "update"]]

答案 1 :(得分:0)

从Miaden的上述答案中找到线索,我使用索引方法进行了粗略的实施

a.sort_by{|x, y| ['Part', 'Plan', 'Inspection'].index(x[0]) <=> ['Part', 'Plan', 'Inspection'].index(y[0]) and ['create', 'update', 'delete', 'release'].index(x[1]) <=> ['create', 'update', 'delete', 'release'].index(y[1])}

=> [["Part", "create"], ["Part", "update"], ["Part", "delete"], ["Part", "release"], ["Plan", "create"], ["Plan", "update"], ["Plan", "delete"], ["Plan", "release"], ["Inspection", "create"], ["Inspection", "update"], ["Inspection", "delete"], ["Inspection", "release"], ["User", "create"], ["User", "update"]]

它可以进一步干涸。