我有一个如下所示的对象:
class Report
attr_accessor :weekly_stats, :report_times
def initialize
@weekly_stats = Hash.new {|h, k| h[k]={}}
@report_times = Hash.new {|h, k| h[k]={}}
values = []
end
end
我想循环遍历weekly_stats和report_times并对每个键进行upcase并为其赋值。
现在我有这个:
report.weekly_stats.map do |attribute_name, value|
report.values <<
{
:name => attribute_name.upcase,
:content => value ||= "Not Currently Available"
}
end
report.report_times.map do |attribute_name, value|
report.values <<
{
:name => attribute_name.upcase,
:content => format_date(value)
}
end
report.values
有没有办法可以在一个循环中映射每周统计数据和报告时间?
由于
答案 0 :(得分:3)
(@report_times.keys + @weekly_stats.keys).map do |attribute_name|
{
:name => attribute_name.upcase,
:content => @report_times[attribute_name] ? format_date(@report_times[attribute_name]) : @weekly_stats[attribute_name] || "Not Currently Available"
}
end
答案 1 :(得分:1)
如果weekly_stats
中保证为nil或空字符串,report_times
中有日期对象,则可以使用此信息来处理合并哈希:
merged = report.report_times.merge( report.weekly_stats )
report.values = merged.map do |attribute_name, value|
{
:name => attribute_name.upcase,
:content => value.is_a?(Date) ? format_date(value) : ( value || "Not Currently Available")
}
end