Ruby代码的效率:月份的哈希+频率到格式化的排序数组

时间:2016-07-22 15:33:29

标签: ruby-on-rails arrays ruby date hash

我已经破解了一些符合其目的的代码,但感觉非常笨重/低效。从许多条目的表中,每个条目都有一个与之相关的月份+年份字符串:" 2016年9月"从这些开始,我创建了一个按时间顺序排列的月份及其频率数据,用于下拉选择表格:[' Novemeber 2016(5)',' 2016年9月(5)&# 39;]

@months = []

banana = Post.pluck(:month)
#array of all months posted in, eg ['September 2016', 'July 2017', etc

strawberry = banana.each_with_object(Hash.new(0)){|key,hash| hash[key] += 1}
#hash of unique month + frequency

strawberry.each { |k, v| strawberry[k] = "(#{v.to_s})" } 
#value into string with brackets

pineapple = (strawberry.sort_by { |k,_| Date.strptime(k,"%b %Y") }).reverse 
#sorts into array of months ordered by most recent

pineapple.each { |month, frequency| @months.push("#{month}" + " " + "#{frequency}") }
#array of formatted months + frequency, eg ['July 2017 (5)', 'September 2016 (5)']

我希望这里的一些Ruby专家可以在某些方面建议我改进这段代码。任何想法或建议将不胜感激!

谢谢!

1 个答案:

答案 0 :(得分:1)

['September 2016', 'July 2017', 'September 2016', 'July 2017']
  .group_by { |e| e } # .group_by(&:itself) since Ruby2.3
  .sort_by { |k, _| Date.parse(k) }
  .reverse
  .map { |k, v| "#{k} (#{v.count})" }

#⇒ [
#  [0] "July 2017 (2)",
#  [1] "September 2016 (2)"
# ]