gpt4 book ai didi

ruby-on-rails - 列中数组的唯一值

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

这篇文章已关闭:

Rails: select unique values from a column

Model.uniq.pluck(:rating)

效果很好,除了在我的例子中,我的列中有一个数组,所以我得到这样的东西:

[["guest"], ["engineer", "manager"], ["engineer"], ["admin"], ["operations"], ["operator"], ["operator", "manager"]]

我希望将这些简化为最简单的列表(按字母顺序排列)。

最佳答案

你需要的是Array#flattenArray#sort

Model.pluck(:rating).flatten
#=>["guest", "engineer", "manager", "engineer", "admin", "operations", "operator", "operator", "manager"]

现在排序:

Model.pluck(:rating).flatten.uniq
#= ["guest", "engineer", "manager", "admin", "operations", "operator"]

Model.pluck(:rating).flatten.uniq.sort
#=> ["admin", "engineer", "guest", "manager", "operations", "operator"]

如果可能有大写单词,在排序时将它们小写,以确保排序不区分大小写:

Model.pluck(:rating).flatten.uniq.sort_by(&:downcase)

关于ruby-on-rails - 列中数组的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34150055/

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