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...)
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
To deliver one more one-liner:
You can use chunk
and one?
[[1,2], [3,4], [7,8], [5,6]].chunk(&:size).one?
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