检查数组元素的大小相同的 [英] Check array's elements are of the same size

查看:141
本文介绍了检查数组元素的大小相同的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有,以检查是否数组元素具有相同的尺寸的最佳且有效的方式?

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

我已经得到了:

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

立刻当它找到一个元素的尺寸与第一种相同的这一次将返回false。

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

这篇关于检查数组元素的大小相同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆