2

次のようなオブジェクトがあります。

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をループし、各キーを大文字にしてその値を割り当てたいと思います。

今私はこれを持っています:

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

1つのループで週次統計とレポート時間の両方をマップする方法はありますか?

ありがとう

4

2 に答える 2

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
于 2013-03-26T18:34:55.903 に答える
1

のnilまたは空の文字列weekly_stats、およびの日付オブジェクトが保証されている場合は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
于 2013-03-26T18:36:20.110 に答える