Equality test on three or more objects

喜欢而已 提交于 2019-12-08 03:59:31

问题


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.


回答1:


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

or

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

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

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



回答2:


[a, b, c, d].group_by(&:itself).length == 1
# => false

or

[a, b, c, d].chunk(&:itself).to_a.length == 1
# => false

or

[a, b, c, d].chunk_while(&:==).to_a.length == 1
# => false

or the naive:

[a, b, c, d].uniq.length == 1

I was reminded of one?. Provided that you do not have any falsy element, the above can be written:

[a, b, c, d].uniq.length.one?



回答3:


I think the answer by @kipar is better by all means, but for the sake of “doing it the way you started” I would post this here:

[a, b, c, d].reduce { |r, e| r == e && r } && true


来源:https://stackoverflow.com/questions/35295181/equality-test-on-three-or-more-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!