我想知道两个 Ruby 数组是否具有相同的元素,但顺序不一定相同。有没有本地方法可以做到这一点? Array 的相等运算符似乎检查项目是否相同以及顺序是否相同,我需要放宽后一个条件。
这个写起来非常容易,我只是想知道是否有本地成语。
最佳答案
如果您也没有重复的项目,您可以使用 Set
而不是 Array
:
Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup.
例子:
require 'set'
s1 = Set.new [1, 2, 3] # -> #<Set: {1, 2, 3}>
s2 = [3, 2, 1].to_set # -> #<Set: {3, 2, 1}>
s1 == s2 # -> true
关于ruby - 比较 Ruby 中的两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16120259/