gpt4 book ai didi

Ruby 数组相等

转载 作者:数据小太阳 更新时间:2023-10-29 08:15:15 27 4
gpt4 key购买 nike

我有一个数组数组,称为 guid_pairs:

[['a','b','c'],['c','g'],['z','f','b']]

我还有一个数组,叫做array_to_check:

['c','a','b']

如何确定数组 guid_pairs 是否有等于 array_to_check 的元素。相等不应该考虑数组元素的位置。

在此示例中,检查应返回 true,因为 guid_pairs 包含元素 ['a','b','c'],它匹配 ['c','a','b']

我已经试过了,但它似乎总是返回 false,即使它应该返回 true:

guid_pairs.any?{|pair| pair.eql?(array_to_check)}

我正在使用 Ruby 1.9.2

最佳答案

有一个set class在标准库中并使用集合非常符合您的意图:

require 'set'

a = ['c','a','b']
aa = [['a','b','c'],['c','g'],['z','f','b']]

find_this = Set.new(a)
the_match = aa.find { |x| find_this == Set.new(x) }

这样就会在the_match中留下aa的匹配元素元素。如果您只对存在感兴趣,那么您可以简单地检查 the_match 的真实性;或使用 any? (感谢 Michael Kohl 的提醒,我经常忘记 Enumerable 中的一些东西):

aa.any? { |x| find_this == Set.new(x) }

没有技巧,没有魔法,使用 Set 可以清楚地表明您实际上是在将数组作为集合进行比较。


顺便说一句,您尝试的解决方案:

guid_pairs.any? { |pair| pair.eql?(array_to_check) }

不起作用,因为数组按顺序逐个元素进行比较,因此当且仅当它们具有相同顺序的相同元素时,两个数组才相等。 documentation for eql?可能更清楚:

Returns true if self and other are the same object, or are both arrays with the same content.

但是== documentation很好很清楚:

Two arrays are equal if they contain the same number of elements and if each element is equal to (according to Object.==) the corresponding element in the other array.

我们可以查看Object#eql?不过需要澄清一下:

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions.

所以 ==eql? 应该表现相同,除非有充分的理由让它们不同。

关于Ruby 数组相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6353156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com