本文介绍了对三个或更多对象进行相等性测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有三个或更多这样的对象:

If I have three or more objects like so:

a = 4
b = 4
c = 4
d = 2

用哪种红宝石风格的方式确定它们是否都相等吗?在三个或更多元素上运行相等性测试的任何定制方法?

what would be a clean ruby-style way of determining whether they are all equal? Any bespoke methods for running equality tests on three or more elements?

我想我可以做这样的事情:

I suppose I could do something like this:

arrays = [a,b,c,d].map{|x| [x]}
arrays.first == arrays.reduce(:&) ? true : false

这似乎有用,但感觉有点麻烦,其他人可能很难开发人员阅读。

which appears to work, but feels sort of ham handed, and might be difficult for other developers to read.

推荐答案

[a,b,c,d].any?{|x| x != a}

array.any?{|x| x != array.first}

或者,全部?某些方法可能更直观:

Alternatively, the #all? method may read more intuitively for some:

array.all? {|x| x == array.first }

这篇关于对三个或更多对象进行相等性测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 07:33