I'm having a bit of a 'problem' with Ruby code. I want to check if all elements of an array are equal.
For example, say I have an array of only 5s:
arr = [5, 5, 5, 5, 5]
I know I can do something like
arr[0] == arr[1] == arr[2] == arr[3] # == arr[4] == ...
but this is impossible for huge arrays and also not very Ruby-like in my opinion. We can improve it by doing something like this:
def all_equal?(arr)
for i in 0..(arr.size-2)
if arr[i] != arr[i+1] then
return false
end
end
true
end
But I also think this is pretty ugly. So is there any built-in/better/shorter (more Ruby-esque) way to do this?
TL;DR what is the shortest/most Ruby-esque way to check if an array contains only one distinct element (e.g. [5, 5, 5]
)?
Thanks.
To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.
In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise. let's look at the syntax… const allEqual = arr => arr.
The Array#intersection method returns a new array containing elements common to both arrays. The order is preserved from original array. Since its a set operation, the resultant array has unique elements.
Ruby | Array class last() function last() is a Array class method which returns the last element of the array or the last 'n' elements from the array.
You could also use .uniq
, that returns an array with no duplicates, and check the size:
def all_equal?(arr)
arr.uniq.size <= 1
end
This works on Ruby 3.0+:
[1,1,1,1].minmax.reduce(&:eql?)
Looks pretty. Might not be the fastest though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With