2013-03-26 2 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 

내가 주간 통계를 모두지도 한 루프에서 시간을보고 할 수있는 방법이 있나요 :

는 지금은이 있나요?

감사합니다 당신이 weekly_stats에 존재하지 않거나 빈 문자열을 보장하고 있으며, report_times의 날짜 객체가, 당신은 병합 된 해시를 통해 작동이 정보를 사용할 수있는 경우

+0

가하는 weekly_stats에는 report_times와 (와) 동일한 attribute_names가 있습니까? –

+0

아니요, 샘플 객체는 @weekly_stats = { "total_transactions => 2", @report_times = { "start_of_week"=> Fri, 15 Mar 2013 00:00:00 EST -05 : 00, "end_of_week"=> Thu, 21 Mar 2013 23:59:59 EST -05 : 00} – BC00

+1

각 해시마다 값을 다르게 처리한다는 사실로 인해 제한을받으며 포함하는 인스턴스의 이름 이외에이 작업을 수행하는 방법을 플래그로 지정할 수 없습니다 변수. –

답변

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에 공통 키가 없다고 가정 –

1

:

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

동일한 키에 문제가 있음을 유의하십시오 –