【问题标题】:How to combine array and hash by date如何按日期组合数组和哈希
【发布时间】:2017-03-16 05:04:03
【问题描述】:

我有一个数组和一个哈希。该数组包含日期,哈希包含一个日期作为键和一个浮点数作为值 (revenue_green)。

这是我的数组:

@reporting_dates = @month_ends.find_all {|e| e < @current_reporting_date.to_s } <<
  @current_reporting_date

还有我的哈希:

@revenue_green = @reports_at_reporting_dates.sum('revenue_green')

这给了我以下输出:

@reporting_dates: ["2017-01-27", "2017-02-24", Fri, 10 Mar 2017]
@revenue_green: {Fri, 10 Mar 2017=>7.0}

对于两个日期 @reporting_dates(2017-01-27 和 2017-02-24)@revenue_green 没有任何值。

我想创建一个哈希值,它会给出以下输出:

@new_hash: {2017-01-27 => 0, 2017-02-24 => 0, 2017-03-10 => 7.0}

所以对于不存在revenue_green 的所有日期,它应该放置一个 0。

我该怎么做?

更新

@month_ends = ["2017-01-27", "2017-02-24", "2017-03-31", "2017-04-28",
               "2017-05-26", "2017-06-30", "2017-07-28", "2017-08-25",
               "2017-09-29", "2017-10-27", "2017-11-24", "2017-12-29"]

@all_dates = (Date.new(@reporting_year).
  beginning_of_year..1.month.from_now).
  to_a.reverse.select { |day| day.wday == 5 }

@current_reporting_date = @all_dates.select { |d| d <= Date.today }.first

@all_reports = Report.all

@reports_at_reporting_dates = @all_reports.where(:day => @reporting_dates).order(:day)

【问题讨论】:

  • 您能否编辑您的答案并将您的代码示例插入为文本而不是图像?
  • 好的,我用代码更新了我的问题。
  • 请阅读“minimal reproducible example”。我们需要最少的代码来复制问题。 @month_ends@current_reporting_date@reports_at_reporting_dates 未定义,因此我们无法运行和测试来帮助您。
  • 好的,我添加了所有缺失的变量。我知道我的代码并不漂亮,但它现在可以工作(我将在我的项目后期重构)
  • 我重新格式化了您的代码,这样读者就不必水平滚动来阅读它。我相信你不会介意的。您的问题涉及@reporting_dates@revenue_green 的值的操作。您如何获得这些值无关紧要。 “这是我的数组”到(但不包括)“我想创建一个哈希......”应该被删除。我不明白您为什么添加“编辑”部分,因为它没有引用上面引用的两个实例变量或@new_hash。我没有看到任何(更不用说所有)变量都需要是实例变量(而不是局部变量)。

标签: ruby-on-rails arrays ruby hash


【解决方案1】:

假设你的起始对象是

@reporting_dates = ["2017-01-27", "2017-02-24", "Fri, 10 Mar 2017"]
@revenue_green = {"Fri, 10 Mar 2017"=>7.0}

(即“2017 年 3 月 10 日星期五”的引号),那么这应该可以工作:

require 'date'
@new_hash = Hash.new
@reporting_dates.each {|d| @new_hash[Date.parse(d)] = @revenue_green[d] || 0}

@new_hash => {#<Date: 2017-01-27 ((2457781j,0s,0n),+0s,2299161j)>=>0, #<Date: 2017-02-24 ((2457809j,0s,0n),+0s,2299161j)>=>0, #<Date: 2017-03-10 ((2457823j,0s,0n),+0s,2299161j)>=>7.0}

或者,如果您希望新哈希中的键是字符串,

@reporting_dates.each {|d| @new_hash[Date.parse(d).strftime("%Y-%m-%d")] = @revenue_green[d] || 0}

@new_hash => {"2017-01-27"=>0, "2017-02-24"=>0, "2017-03-10"=>7.0}

【讨论】:

  • 通过这个解决方案我得到了一个新的哈希值,但是所有的值都是 0
  • 我在 ruby​​ 2.2.3 中运行了我发布的所有代码,并获得了我发布的@new_hash,两个版本。
  • 刚刚将“@reporting_dates: ...”更改为“@reporting_dates = ...”以使代码更易于复制和粘贴。
  • 我成功了!!我不得不将@revenue_green[d] 更改为@revenue_green[d.to_date]。如果您更新您的解决方案,我点击接受答案。谢谢!
  • @Oliver,你显然在使用 rails,因为 to_date 不是纯 Ruby 中的 String 方法。但是我不能凭良心改变我的答案,因为它可以在 irb 和 rails 控制台中使用您提供的原始参数(即没有“.to_date”)正常工作(可以说在 rails 控制台中更好,因为您不需要“要求'日期'”)。 repl.it/GX3u/0跟随你的心。
猜你喜欢
  • 2015-03-25
  • 1970-01-01
  • 2020-02-13
  • 2016-03-30
  • 2020-02-17
  • 1970-01-01
  • 2020-07-24
  • 2019-03-03
  • 2021-11-23
相关资源
最近更新 更多