将x元素移动到数组的末尾

时间:2017-09-03 18:13:20

标签: arrays ruby arel

我正在尝试找到一种方法来获取特定关系并将其移动到数组的末尾。基本上,我有一个current_account,我想把这个帐户移到帐户关系数组的末尾,这样当我迭代关系时它会显示在最后。我希望制作一个范围并尽可能使用SQL,这是我的尝试,我还没有真正得到任何地方。

HTML

<% current_user.accounts.current_sort(current_account).each do |account| %>
   <li><%= link_to account.name, switch_account_accounts_path(account_id: account.id) %></li>
<% end %>

此当前返回按created_at帐户排序的列表。我不希望它按创建时排序,但current_account位于底部,所以我创建了一个名为current_sort的范围,但我不知道该怎么做。

帐户的CURRENT_SORT范围

 scope :current_sort, lambda { |account|

 }

我希望此范围在关联数组中最后返回传入的帐户。我怎么能用SQL或Ruby做到这一点?

2 个答案:

答案 0 :(得分:4)

将特定元素排序到数组末尾的快速技巧是:

array.sort_by { |v| v == current_account ? 1 : 0 }

如果您想移动多个元素,则更容易:

to_end = [ a, b ]

array - to_end + to_end

编辑:正如Stefan指出的那样,这可能会重新订购商品。解决这个问题:

array.sort_by.with_index do |v, i|
  v == current_account ? (array.length + i) : i
end

您也可以使用partition以不同的方式处理它:

array.partition { |v| v != current_account }.reduce(:+)

这是Stefan在回答中使用的方法的变体。

答案 1 :(得分:2)

您可以使用partition按条件拆分数组。

array = [1, 2, 3, 4, 5, 6, 7, 8]
current_account = 3

other_accounts, current_accounts = array.partition { |v| v != current_account }
#=> [[1, 2, 4, 5, 6, 7, 8], [3]]

other_accounts
#=> [1, 2, 4, 5, 6, 7, 8]

current_accounts
#=> [3]

结果可以连接起来:

other_accounts + current_accounts
#=> [1, 2, 4, 5, 6, 7, 8, 3]

或单行:

array.partition { |v| v != current_account }.flatten(1)
#=> [1, 2, 4, 5, 6, 7, 8, 3]

# or

array.partition { |v| v != current_account }.inject(:+)
#=> [1, 2, 4, 5, 6, 7, 8, 3]