有一个更好的替代方法来查找数组是否为2d数组.
my_array = [["a", "b"],["c", "d"],["e", "f"]] !my_array.map{|element| element.is_a? Array}.include? false
有任何想法吗?
我假设通过"2d数组"(在Ruby中没有任何意义),OP想要确定数组的每个元素是否都是一个数组,并且所有这些元素数组都是相同的大小,就像" 2d矩阵".
编辑2:这是另一种方式(比我原来的答案要好得多!):
def all_elements_arrays_of_same_size?(a) !!(a.transpose rescue nil) end all_elements_arrays_of_same_size? [["a", "b"],["c", "d"],["e", "f"]] #=> true all_elements_arrays_of_same_size? [["a", "b"],["c", "d", "g"],["e", "f"]] #=> false all_elements_arrays_of_same_size? [["a", "b"],"c",["e", "f"]] #=> false all_elements_arrays_of_same_size? [["a", "b"],"c", {a:1}] #=> false all_elements_arrays_of_same_size? [[1,2,3,4,5,6,7,8], 1] #=> false
编辑1: @WandMaker提出了一个非常好的观点[关于我原来的答案].以前我曾经a.map(&:size).minmax.uniq.size
.我minimax
按照他的建议删除了.]
我假设"2D数组"是一个数组,其元素是相同大小的数组.
def all_elements_arrays_of_same_size?(a) a.all? { |e| e.class==Array } && a.map(&:size).uniq.size == 1 end all_elements_arrays_of_same_size? [["a", "b"],["c", "d"],["e", "f"]] #=> true all_elements_arrays_of_same_size? [["a", "b"],["c", "d", "g"],["e", "f"]] #=> false all_elements_arrays_of_same_size? [["a", "b"],"c",["e", "f"]] #=> false all_elements_arrays_of_same_size? [["a", "b"],"c", {a:1}] #=> false all_elements_arrays_of_same_size? [[1,2,3,4,5,6,7,8], 1] #=> false
对于最后一个例子,请注意[1,2,3,4,5,6,7,8].size #=> 8
和1.size #=> 8
.
步骤如下:
对于:
array = [["a", "b"],["c", "d"],["e", "f"]] array.all? { |e| e.class==Array } #=> true a = array.map(&:size) #=> [2, 2, 2] b = a.uniq #=> [2] b.size == 1 #=> true
另一方面,对于:
array = [["a", "b"],["c", "d", "g"],["e", "f"]] array.all? { |e| e.class==Array } #=> true a = array.map(&:size) #=> [2, 3, 2] b = a.uniq #=> [2, 3] b.size == 1 #=> false
对于:
array = [["a", "b"],"c", {a:1}] array.all? { |e| e.class==Array } #=> false