Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality test on three or more objects

Tags:

equality

ruby

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.

like image 220
boulder_ruby Avatar asked May 15 '26 01:05

boulder_ruby


1 Answers

[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 }
like image 86
kipar Avatar answered May 17 '26 15:05

kipar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!