Ruby方法与局部变量的简单的重构 - Ruby method with local variable - a case of simple refactoring

- 此内容更新于:2016-02-02
主题:

目前我的方法是这样的:它看起来很丑,但是我需要回报。想让比尔一个实例变量,因此定义它当我的对象初始化,但我不使用它。什么最好的方法重构呢?

原文:

My method is currently like this:

def calculate
  bill = 0
  order.each {|k, v| bill += restaurant.show_menu[k]*v}
  bill  
end

It looks really ugly, but I need it to return bill. Thought about making bill an instance variable and hence define it when my object initializes, but I don't use it anywhere else. Whats the best way to refactor this?

网友:看来这个方法,但是你没有提供解释。请详细说明。

(原文:It appears that order and restaurant are methods, but you've provided no explanation. Please elaborate.)

网友:为什么你认为它是upgly?局部变量是什么毛病?

(原文:why you think it is upgly? what is wrong with local variables?)

网友:有一些Ruby方法来解决这种问题。

(原文:There are few Ruby ways to solve exactly this kind of problem.)

网友:@Meier,与局部变量并没有什么错,但每次使用一个还有一个潜在的错误来源。例如,如果在一个地方有,后来拼错变量写(不可能),你有一个bug,南瓜。

(原文:@Meier, there's nothing wrong with local variables, but each time one is used there's one more potential source of errors. If, for example, in one place you had ugly = 4 and later misspelled the variable and wrote upgly = 7 (improbable as that might be), you've got one more bug to squash.)

解决方案:
这是一个可能的方法:
原文:

Here is one possible way:

 def calculate
    order.reduce(0) {|bill, (k, v)| bill + restaurant.show_menu[k]*v}
 end
网友:谢谢你!我之前看过减少方法但是我不知道使用它对于这种情况。

(原文:thank you. I've seen reduce method before but I didn't know to use it for this case.)

楼主:@ggwc你可能想要接受一个答案如果它帮助..看一看如何接受一个答案。你会得到+2分,许多新用户似乎错过接受的答案。你以前的问题有一个很好的答案,请接受这一个。可以等待几个小时或几天前接受如果你不满意当前的答案。

(原文:@ggwc You may want to accept an answer if it helps.. Have a look at how to accept an answer. You will get +2 points, many new users seems to miss on accepting answers. Your previous question had a good answer, please accept that one as well. It's okay to wait for few hours or few days before accepting if you are not satisfied with current answers.)

网友:@ggwc还可以单独使用的步骤,如

(原文:@ggwc you can also separate the steps using map and reduce, e.g. order.map { |k, v| restaurant.show_menu[k] * v }.reduce(0, :+))

解决方案:
返回一个数组包含的值;在每个元素上应用的方法,这意味着总结。
原文:
def calculate
  order.map { |k, v| restaurant.show_menu[k] * v }.reduce(:+)
end

map to return an array contains of the values; reduce to apply the :+ method on each element, which means to sum them up.