Equality test on three or more objects

情到浓时终转凉″ 提交于 2019-12-06 07:33:42
kipar
[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 }
[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?

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