我有一组哈希保存到数据库中。日期采用DateTime格式。
@item.yearly_interest_totals = [
{"financial_year" => "Sun, 01 Jan 2017 00:00:00 +0000", "total" => "360"},
{"financial_year" => "Mon, 01 Jan 2018 00:00:00 +0000", "total" => "240"},
{"financial_year" => "Tue, 01 Jan 2019 00:00:00 +0000", "total" => "240"}
]
在我看来,我在变量financial_year中有一个特定的财政年度
如何使用financial_year键显示相应的值?关于将财务年度整数与DateTime对象进行比较,我有点困惑......
例如:
<tr>
<td>Financial Year: <%= financial_year.to_i %></td>
<td><%= @item.yearly_interest_totals.find{|i| i["financial_year"] == DateTime.new(financial_year.to_i,1,1)}["total"] %></td>
</tr>
这应显示为:
财政年度:2017年360
仅供参考:Rails 5.0.0.1,Ruby 2.3.1,本地Postgres DB
答案 0 :(得分:0)
假设:
financial_year = 2017
然后你可以这样做:
@items.yearly_interest_totals.each do |yit|
yit.merge!(DateTime.strptime(yit['financial_year'], "%a, %d %b %Y %H:%M:%S %z").year => yit['total'])
end
#=>[
# {"financial_year"=>"Sun, 01 Jan 2017 00:00:00 +0000", "total"=>"360", 2017=>"360"},
# {"financial_year"=>"Mon, 01 Jan 2018 00:00:00 +0000", "total"=>"240", 2018=>"240"},
# {"financial_year"=>"Tue, 01 Jan 2019 00:00:00 +0000", "total"=>"240", 2019=>"240"}
# ]
现在在你看来:
<tr>
<td>Financial Year: <%= financial_year %></td>
<td><%= @item.yearly_interest_totals.find{|yit| yit[financial_year] }[financial_year] %></td>
</tr>
请注意,我假设你在另一个财政年度的循环中显示这个,然后上面的解决方案使O(n2)的时间复杂度,这不是一个有效的方法,否则它的工作。
如果我们可以将此数组更改为哈希哈希值,那么它对于大型数据集可以更好地工作:
yearly_interest_totals = @items.yearly_interest_totals.each_with_object({}) do |yit, obj|
obj[DateTime.strptime(yit['financial_year'], "%a, %d %b %Y %H:%M:%S %z").year] = yit
end
# =>
# {
# 2017=>{"financial_year"=>"Sun, 01 Jan 2017 00:00:00 +0000", "total"=>"360"},
# 2018=>{"financial_year"=>"Mon, 01 Jan 2018 00:00:00 +0000", "total"=>"240"},
# 2019=>{"financial_year"=>"Tue, 01 Jan 2019 00:00:00 +0000", "total"=>"240"}
# }
现在在你看来:
<tr>
<td>Financial Year: <%= financial_year %></td>
<td><%= yearly_interest_totals[financial_year]['total'] %></td>
</tr>
如果您有一年的多个财务数据,那么我建议您将yearly_interest_totals
散列值作为数组或更新总数(以适用者为准)。
答案 1 :(得分:0)
financial_year = 2018
yearly_interest_totals.map do |t|
t["total"] if Date.parse(t["financial_year"]).year == financial_year
end.compact
#⇒ ["240"]
yearly_interest_totals.detect do |t|
Date.parse(t["financial_year"]).year == financial_year
end["total"]
#⇒ "240"