我有以下代码
def calculate_metrics
reach_values = {}
reach_values['reach_change_value'] = 0
reach_values['reach_change_type'] = 'nochange'
if find_yesterdays_metrics
change = (get_influencer_metrics["total_count"]).to_i - find_yesterdays_metrics.reach_count
reach_values['reach_change_value'] = change.abs
case
when change < 0
reach_values['reach_change_type'] = "down"
when change > 0
reach_values['reach_change_type'] = "up"
end
end
reach_values
end
def set_metrics_data
@facebook_metrics = @influencer_metrics.new(
reach_change_value: calculate_metrics['reach_change_value'],
reach_change_type: calculate_metrics['reach_change_type'],
social_account: SocialAccount.friendly.find('facebook')
)
end
现在正在调用calculate_metrics
两次并完全处理两次。有没有关于如何优化相同的建议,以便我不必两次处理相同的数据。
答案 0 :(得分:1)
在set_metrics_data
中将calculate_metrics的结果放入tmp变量中,让我们调用它x
,然后询问x
的类型和值。看起来像是:
x = calculate_metrics
reach_change_value : x['reach_change_value']
each_change_type : x['reach_change_type']`
因此,对calculate_metrics的调用仅被调用一次(并存储在tmp变量x
中)。
答案 1 :(得分:0)
你可以按照
这样的M. Suurland回答x = calculate_metrics
reach_change_value : x['reach_change_value']
each_change_type : x['reach_change_type']`
对于某些优化/语法更改calculate_metrics,您可以像这样使用
def calculate_metrics
reach_values = {'reach_change_value': 0, 'reach_change_type': "nochange"}
yesterday_mat = find_yesterdays_metrics
if yesterday_mat
change = (get_influencer_metrics["total_count"]).to_i - yesterday_mat.reach_count
reach_values =
case change
when change < 0
{'reach_change_type': "down", 'reach_change_value': change.abs}
when change > 0
{'reach_change_type': "up", 'reach_change_value': change.abs}
else
reach_values
end
end
reach_values
end