gpt4 book ai didi

Ruby:根据条件拆分/排序数组

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

我有一系列假期:

Holiday.all                        
Holiday Load (0.7ms) SELECT "holidays".* FROM "holidays"
=> #<ActiveRecord::Relation [#<Holiday id: 1, name: "Dia da Confraternização Universal", holidayable_id: 1, holidayable_type: "Country", date: "2014-01-01", created_at: "2014-11-05 21:38:13", updated_at: "2014-11-05 21:38:13", verified?: false>, #<Holiday id: 2, name: "Natal", holidayable_id: 1, holidayable_type: "Country", date: "2014-12-25", created_at: "2014-11-05 22:02:33", updated_at: "2014-11-05 22:02:33", verified?: false>]>

我想按日期月份拆分这一大日期数组,所以我最终得到 12 个数组(每个月一个)。

最佳答案

您要使用的是 Enumerable#group_by方法。

Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block and the values are arrays of elements in the collection that correspond to the key.

If no block is given an enumerator is returned.

(1..6).group_by { |i| i%3 }   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}

例如

["12/25", "01/01", (...)].group_by { |date| date.split("/").first } 

关于Ruby:根据条件拆分/排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26768433/

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