-2

我有一个数组

[['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 实现了动态角色和权限。需要为用户分配操作(创建、更新、删除、发布)的权限,并且主题类(零件、计划、检查、用户)的显示顺序必须与其关系相同。

当我使用排序时,我得到

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"]] 

可以以某种方式使用索引方法吗?以后可能还会添加新的主题类和操作。所以排序顺序可能会改变。

4

2 回答 2

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"]]
于 2012-10-10T08:24:40.663 回答
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"]]

它可以进一步干燥。

于 2012-10-10T08:37:14.827 回答