从数组中删除键并使其最后使用的最快方法

问题描述 投票:0回答:3

我必须从最初按字母顺序排序的数组中删除“其他”类别,然后使其成为最后一个索引。我创建了这个小帮手,但相信可以有更快的方法来完成此任务。

该数组是这样的[#<Category id: 17, title: "Books">, #<Category id: 18, title: "Children's Clothing">,

这是我所做的。有用。虽然,我想知道是否有更有效的方法。

<%
@options = []
@other_option = []

@free_item_options.each do |category|
    if category.title.downcase == "other"
      @other_option << category
    else
      @options << category
    end
end

@options << @other_option[0]
%>
ruby-on-rails ruby ruby-on-rails-5
3个回答
2
投票

在这种情况下,我通常会进行多参数排序。

@free_item_options.sort_by do |option|
  [
    option.title.casecmp?('other') ? 1 : 0,
    option.title,
  ]
end

“其他”类别将有1,并且将排在最后。其他所有内容都将为0,并且它们之间将按标题升序排序。


0
投票

另一种方法是只使用SQL。

@free_item_options = Category.select("categories.*, (LOWER(title) = 'other') as is_other").order('is_other', :title).to_a

0
投票

Enumerable#partition,旨在将集合分成两个分区。

Enumerable#partition

如果您确定最多有一个“其他”类别(根据@other_option, @options = @free_item_options.partition { |category| category.title.casecmp?('other') } @options.concat(@other_options) 似乎是这种情况)。您也可以将@options << @other_option[0]find_indexfind_index结合使用。 delete_at在第一个比赛时停止重复。

delete_at

请记住,以上内容确实会使<<发生突变。

© www.soinside.com 2019 - 2024. All rights reserved.