从两个日期值之间的哈希数组中获取一组哈希值

时间:2016-10-04 10:43:27

标签: ruby-on-rails ruby hash

我有一个包含日期和总密钥的哈希数组。

例如:

hash = [{
  "Date"=>"01/01/2016",
  "Total"=>10
},{
  "Date"=>"02/01/2016",
  "Total"=>20
},{
  "Date"=>"03/01/2016",
  "Total"=>30
},{
  "Date"=>"04/01/2016",
  "Total"=>40
},{
  "Date"=>"05/01/2016",
  "Total"=>50
}]

我想要做的是将两个日期传递给一个方法,然后只返回其日期匹配或两个日期之间的哈希值。

例如:

get_data(startDate, endDate)

end

startDate和endDate为'02 / 01/206'且04/01/2016

会回来:

{
  "Date"=>"02/01/2016",
  "Total"=>20
},{
  "Date"=>"03/01/2016",
  "Total"=>30
},{
  "Date"=>"04/01/2016",
  "Total"=>40
}

2 个答案:

答案 0 :(得分:2)

def get_data(start_date, end_date, hash)
  hash.select{|entry| entry["Date"].to_date.between?(start_date.to_date, end_date.to_date) }
end

答案 1 :(得分:0)

我支持@Steve的回答,但我想指出你可以使用Ruby有些模糊flip-flop operator

下面,arr是示例中的哈希数组。

require 'date'

h = arr.each_with_object({}) { |g,h| h[Date.strptime(g["Date"], '%d/%m/%Y')] = g }
  #=> {#<Date: 2016-01-01 ((2457389j,0s,0n),+0s,2299161j)>=>
  #      {"Date"=>"01/01/2016", "Total"=>10},
  #    #<Date: 2016-01-02 ((2457390j,0s,0n),+0s,2299161j)>=>
  #      {"Date"=>"02/01/2016", "Total"=>20},
  #    #<Date: 2016-01-03 ((2457391j,0s,0n),+0s,2299161j)>=>
  #      {"Date"=>"03/01/2016", "Total"=>30},
  #    #<Date: 2016-01-04 ((2457392j,0s,0n),+0s,2299161j)>=>
  #      {"Date"=>"04/01/2016", "Total"=>40},
  #    #<Date: 2016-01-05 ((2457393j,0s,0n),+0s,2299161j)>=>
  #      {"Date"=>"05/01/2016", "Total"=>50}}  

range =  Date.strptime('02/01/2016', '%d/%m/%Y')..Date.strptime('04/01/2016', '%d/%m/%Y')
  #=> #<Date: 2016-01-02 ((2457390j,0s,0n),+0s,2299161j)>..
  #   #<Date: 2016-01-04 ((2457392j,0s,0n),+0s,2299161j)> 

触发器操作符用于确定属于给定范围的键:

keeper_keys = h.keys.sort.select { |d| range.include?(d) .. true ? true : false }
  #=> [#<Date: 2016-01-02 ((2457390j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2016-01-03 ((2457391j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2016-01-04 ((2457392j,0s,0n),+0s,2299161j)>]

h.select { |k,_| keeper_keys.include?(k) }.values
  #=> [{"Date"=>"02/01/2016", "Total"=>20},
  #    {"Date"=>"03/01/2016", "Total"=>30},
  #    {"Date"=>"04/01/2016", "Total"=>40}]