2013-03-26 91 views
1

我有一個對象,看起來像下面:紅寶石,地圖,對象屬性

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

做weekly_stats與report_times具有相同的attribute_names? – 2013-03-26 18:16:10

+0

不,它沒有,樣本對象將@weekly_stats = {「total_transactions => 2},@report_times = {」start_of_week「=>星期五,2013年3月15日00:00:00 EST -05:00,」end_of_week「=>星期四,2013年3月21日23:59:59 EST -05:00} – BC00 2013-03-26 18:18:33

+1

您受限於您爲每個散列值處理值不同的事實,並且沒有辦法標記除包含實例的名稱之外如何執行此操作變量 – 2013-03-26 18:29:31

回答

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 
+0

假設report_times和weekly_stats沒有共同的密鑰 – 2013-03-26 18:36:38

1

如果你保證零或空字符串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 
+0

注意這也存在問題相同的鍵 – 2013-03-26 18:38:26