Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 297
InputUsername Avatar asked Dec 14 '14 16:12

InputUsername


People also ask

How do you check if all values in an array are equal?

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.

How do you check if all elements in an array are equal in typescript?

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.

How do you find the common element in two arrays in Ruby?

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.

What does .last do in Ruby?

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.


2 Answers

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
like image 133
Luan Nico Avatar answered Sep 20 '22 04:09

Luan Nico


This works on Ruby 3.0+:

  [1,1,1,1].minmax.reduce(&:eql?)

Looks pretty. Might not be the fastest though.

like image 27
sreedev Avatar answered Sep 20 '22 04:09

sreedev