我有数据:
data = [["/","201408","41"],["/","201409","35"],["/","201410","59"],["/","201411","50"],["/","201412","79"],["/","201501","97"],["/","201502","85"],["/","201503","518"],["/","201504","251"],["/","201505","748"],["/","201506","916"],["/","201507","1008"],["/","201508","449"],["/","201509","235"],["/","201510","195"],["/","201511","229"],["/","201512","202"],["/","201601","142"],["/","201602","134"],["/","201603","17"]]
我想按年份对它们进行分组,但我不知道如何在group_by
中使用正则表达式。我应该这样:
grouped = data.group_by { |row| row[1] }
但下一步是什么? row [1]字符串是YYYYMM
答案 0 :(得分:1)
为什么需要正则表达式?这不是你想要的吗?
data.group_by { |d| d[1][0..3] }
答案 1 :(得分:0)
我更喜欢幻觉'回答,但如果你还想使用正则表达式:
data.group_by { |row| row[1].match(/^(\d{4})/).captures[0] }
不是很干净,但是有效。