Ruby-on-rails 如何比较两个数组的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5514142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare content of two arrays?
提问by Trip
I am comparing zip codes.
我正在比较邮政编码。
I have three constants of zip codes :
我有三个邮政编码常量:
ZIP_MORRIS
ZIP_UNION
ZIP_ESSEX
I want to see if a user has in an Object's array, all the zips included in one of those.
我想看看用户是否在一个对象的数组中,所有的 zip 都包含在其中一个中。
I tried this:
我试过这个:
ZIP_UNION.sort{|x,y| y <=> x} <=> Email.find(3).distributions.map(&:zip_code).uniq.compact.sort{|x,y| y <=> x}
But unfortunately, this just maps all the zip codes, so if I were to choose one extra zip in a different county, then it would not properly compare them.
但不幸的是,这只是映射了所有的邮政编码,所以如果我要在不同的县选择一个额外的邮政编码,那么它就无法正确比较它们。
I think the best solution would be to compare the values of the User Generated Zips, and see if all of the zips in one ZIP_COUNTYare present inside the array.
我认为最好的解决方案是比较用户生成的 Zip 的值,并查看一个 ZIP_COUNTY中的所有 zip是否都存在于数组中。
Some kind of iterator that would run through all the zips and ensure that the user's zip do or do not include every single zip in a zip group.
某种迭代器将运行所有 zip 并确保用户的 zip 包含或不包含 zip 组中的每个单独的 zip。
Any ideas?
有任何想法吗?
回答by Michael Kohl
You can do array differences, if the result is the empty array, the 2 arrays contained the same elements:
您可以进行数组差异,如果结果是空数组,则两个数组包含相同的元素:
>> [1,2,3]-[3,1,2] #=> []
If you still have elements left, then not all elements of the first array were present in the second one:
如果您仍然有元素,那么并非第一个数组的所有元素都出现在第二个数组中:
>> [1,2,5]-[3,1,2] #=> [5]
回答by Jesse Wolgamott
Below I'm using the all? operator on an array, which will return true if all of the items in the array return true for the block I'm passing in.
下面我用的是all? 数组上的运算符,如果数组中的所有项都为我传入的块返回真,则该运算符将返回真。
my_zip = [1,2,3,4,5,6]
[2,3,5].all?{|z| my_zip.include?(z)}
=> true
[20,3,5].all?{|z| my_zip.include?(z)}
=> false
You'd just change it up to be the user's zip codes
您只需将其更改为用户的邮政编码
回答by carbonr
> [1,2,3] <=> [1,2,3]
=> 0
> [1,2,3] <=> [2,2,3]
=> -1
> [1,2,3] <=> [3,2,3]
=> -1
> [1,2,3] <=> [1,3,3]
=> -1
> [1,2,3] <=> [1,1,3]
=> 1
this is from RailsThinker Postand has been working for me very well.
这是来自RailsThinker Post并且一直对我来说有效得很好。
回答by Даниэль Сайфулин
One more decision
又一个决定
arr1 = [3,2,1]
arr2 = [2,1,3]
arr1.sort == arr2.sort # => true
arr2 = [2,1,2]
arr1.sort == arr2.sort # => false

