InputUsername InputUsername - 4 months ago 11
Ruby Question

Ruby: check if all array elements are equal

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.

Answer

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
Comments