Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check array's elements are of the same size

Tags:

arrays

ruby

is there a best and efficient way to check if array's elements are of the same size?

[[1,2], [3,4], [5]] => false

[[1,2], [3,4], [5,6]] => true

What I've got:

def element_of_same_size?(arr)
  arr.map(&:size).uniq.size == 1
end

Another solution:

def element_of_same_size?(arr)
  arr[1..-1].each do |e|
    if e.size != arr.first.size
      return false
    else
      next
    end
  end
  return true
end

This one will return false immediately when it finds a element is not the same size as the first one.

Is there a best way to do this? (Of course...)

like image 208
Juanito Fatas Avatar asked Dec 01 '22 03:12

Juanito Fatas


2 Answers

What about using the Enumerable#all? method?

def element_of_same_size?(arr)
  arr.all? { |a| a.size == arr.first.size }
end

element_of_same_size?([[1,2], [3,4], [5]])
# => false

element_of_same_size?([[1,2], [3,4], [5, 6]])
# => true
like image 69
toro2k Avatar answered Dec 15 '22 13:12

toro2k


To deliver one more one-liner:

You can use chunk and one?

[[1,2], [3,4], [7,8], [5,6]].chunk(&:size).one?
like image 21
Beat Richartz Avatar answered Dec 15 '22 14:12

Beat Richartz