gpt4 book ai didi

ruby-on-rails - 从数组中删除键并使其持久的最快方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:27 24 4
gpt4 key购买 nike

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

数组是这样的[#<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]
%>

最佳答案

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

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

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

关于ruby-on-rails - 从数组中删除键并使其持久的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58646004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com