gpt4 book ai didi

ruby-on-rails - 按 bool 值分组但在 ruby​​ on rails 中更改键

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

我正在按 bool 值的 before 属性对数组进行排序,这是可行的,但我宁愿不使用 true 和 false 作为哈希值,而是在 true 时使用“before”,在 before 等于 false 时使用“after”

a.each { |x| arr << x.answers.group_by(&:before) unless x.answers == nil }

有没有简单的方法可以做到这一点?

即不是 true: [], false: []我更喜欢 before: [], after: []

最佳答案

当然是这样

x.answers.group_by {|e| e.before ? :before : :after}

这将创建一个 Hash{before: [],after:[]}

例如。

a = [1,2,3,4,5,6,7]
a.group_by {|n| n.odd? ? :odd : :even}
#=> {odd: [1, 3, 5, 7], even: [2, 4, 6]}

#group_by处理来自 block 的返回响应,所以 truefalse成为键,但您可以用任何您喜欢的东西替换响应,这些将充当键。这意味着您可以有 2 个以上的返回,例如

a = [1,2,3,4,5,6,7]
a.group_by {|n| n == 2 ? :two : n == 3 ? :three : n.odd? ? :odd : :even}
#=> {:odd=>[1, 5, 7], :two=>[2], :three=>[3], :even=>[4, 6]}

我使用三元运算符来节省空间我不建议将它们嵌套得这么深,因为它会降低可读性这只是一个例子。

关于ruby-on-rails - 按 bool 值分组但在 ruby​​ on rails 中更改键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28681668/

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