两种方式比较一组哈希

时间:2017-01-13 17:52:50

标签: ruby-on-rails ruby

添加这个是因为有些人没有看到我要求的内容,但我在寻找每个数组中的唯一值,与其他数组相比。

我需要找到saved_startincoming_start之间的差异,以及incoming_startsaved_start之间的差异。 saved_start是数据库查询的结果,而incoming_start是来自webhook的params的结果。以下是两个开头的数组:

saved_start = [{id: "12345", qty: 25}, {id: "678", qty: 20}]
incoming_start = [{id: "12347", qty: 25}, {id: "678", qty: 20}, {id: "abc", qty: 20}]

我发现了数组之间的差异:

in_array = incoming_start - saved_start
saved_array = saved_start - incoming_start

以上回报:

in_array => [{:id=>"12347", :qty=>25}, {:id=>"abc", :qty=>20}]
saved_array => [{:id=>"12345", :qty=>25}]

然后遍历它们以查找in_array id 12347abcsaved_array没有saved_array。虽然id12345 in_arrayin_array却没有。数量也是如此。

如果saved_arrayin_array.each do |incoming| saved_array.each do |saved| pp "Does the saved hash have the id #{incoming[:id]} #{saved.has_value?(incoming[:id])}" pp "Does the saved hash have the quantity of #{incoming[:qty]} #{saved.has_value?(incoming[:qty])}" end end 的大小相同,则效果很好。如果没有,它会破裂。

in_array

以上效果很好,因为saved_array大于saved_array

以下内容会返回错误数据,因为saved_array.each do |saved| in_array.each do |incoming| pp "Does the incoming hash have the id #{saved[:id]} #{incoming.has_value?(saved[:id])}" pp "Does the incoming hash have the quantity of #{saved[:qty]} #{incoming.has_value?(saved[:qty])}" end end 较小。

saved_start

在英语中,我需要让incoming_start包含与saved_start相同的数据。

但为了做到这一点,我需要知道incoming_start中不在saved_start内的内容,以便我可以从id删除它。然后找出< incoming_start'中的内容。那不在' saved_start'所以我可以添加它。然后最终qty中的incoming_start可能saved_start在[{1}}中有所不同,因此我需要更新$post->averageRating()

噢..

由于

1 个答案:

答案 0 :(得分:0)

您好希望以下代码可能有所帮助。此代码将:(01) - 数组1中的点值未在数组2中找到...(02) - 数组2中的点值在数组1中找不到...(03) - 存储数组2中的所有唯一值。 ...对于问题的描述,我认为这是你正在寻找的,为了使事情更容易,我将数组重命名为:arr1& ARR2。

<script src="cordova.js"></script>

我希望这会有所帮助。 ;)

相关问题