计算来自两个不同哈希的总数 [英] Calculating totals from two different hashes

查看:82
本文介绍了计算来自两个不同哈希的总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个哈希值:

例如,其中包含一道菜及其价格列表

For example, one contains a list of dishes and their prices

dishes = {"Chicken"=>12.5, "Pizza"=>10, "Pasta"=>8.99}

另一个是篮子杂菜,即我选择了一个面食和两个披萨:

The other is a basket hash i.e. I've selected one pasta and two pizzas:

basket = {"Pasta"=>1, "Pizza"=>2}

现在,我正在尝试计算购物篮的总费用,但似乎无法正确地获得我的推荐信.

Now I am trying to calculate the total cost of the basket but can't seem to get my references right.

尝试过

basket.inject { |item, q| dishes[item] * q }

但是继续出现以下错误

NoMethodError:nil:NilClass的未定义方法'*'

NoMethodError: undefined method `*' for nil:NilClass

推荐答案

basket.inject { |item, q| dishes[item] * q }

让我们看一下 Enumerable#inject 的文档看看发生了什么. inject通过采用起始对象",然后将二进制操作重复应用于起始对象和第一个元素,然后对该对象和第二个元素的结果,再对对象进行折叠",将集合折叠为单个对象. that 和第三个元素的结果,等等.

Let's look at the documentation for Enumerable#inject to see what is going on. inject "folds" the collection into a single object, by taking a "starting object" and then repeatedly applying the binary operation to the starting object and the first element, then to the result of that and the second element, then to the result of that and the third element, and so forth.

因此,该块接收两个参数:累加器的当前值和当前元素,并且该块返回该累加器的新值,以供下一次调用该块.如果不为累加器提供起始值,则使用集合的第一个元素.

So, the block receives two arguments: the current value of the accumulator and the current element, and the block returns the new value of the accumulator for the next invocation of the block. If you don't supply a starting value for the accumulator, then the first element of the collection is used.

因此,在这里的第一次迭代中,由于您没有为累加器提供起始值,因此该值将成为第一个元素;迭代将从第二个元素开始.这意味着在第一次迭代期间,item将是['Pasta', 1],而q将是['Pizza', 2].让我们来看一下示例:

So, during the first iteration here, since you didn't supply a starting value for the accumulator, the value is going to be the first element; and iteration is going to start from the second element. This means that during the first iteration, item is going to be ['Pasta', 1] and q is going to be ['Pizza', 2]. Let's just run through the example in our heads:

dishes[item] * q                    # item is ['Pasta', 1]
dishes[['Pasta', 1]] * q            # q is ['Pizza', 2]
dishes[['Pasta', 1]] * ['Pizza', 2] # there is no key ['Pasta', 1] in dishes
nil * ['Pizza', 2]                  # nil doesn't have * method

Ergo,您得到一个NoMethodError.

Ergo, you get a NoMethodError.

现在,我相信,您实际上想要做的是这样的事情:

Now, I believe, what you actually wanted to do was something like this:

basket.inject(0.0) {|sum, (item, q)| sum + dishes[item] * q }
#             ↑↑↑    ↑↑↑             ↑↑↑↑↑

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆