在红宝石多维数组的尺寸越来越 [英] getting dimension of multidimensional array in ruby

查看:111
本文介绍了在红宝石多维数组的尺寸越来越的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习红宝石。
现在我需要找出一个多维数组的维度。我看了一下红宝石文档的所有阵列的方法,但我找不到返回维度的方法。

I just started learning ruby. Now I need to figure out the dimension of a multidimensional array. I had a look at ruby-docs for the all the array methods, but I could not find a method that returns the dimension.

下面是一个例子:

有关 [1,2],[3,4],[5,6]] 尺寸应为2。

有关 [[[1,2],[2,3],[3,4],[5]]] ,尺寸应该是3

推荐答案

有不是一个内置的功能可能有多种定义,以你的意思是维一个数组的东西。 Ruby的数组可以包含任何东西,包括散列或其他数组。这就是为什么我相信你需要实现你自己的功能。

There is not a built-in function for that as there may be multiple definition as to what you mean by "dimension" for an array. Ruby's arrays may contain anything including hashes or other arrays. That's why I believe you need to implement your own function for that.

Asuming,通过维你的意思是数组的嵌套最深层次这应该做的伎俩:

Asuming that by dimension you mean "the deepest nested level of arrays" this should do the trick:

def get_dimension a
  return 0 if a.class != Array
  result = 1
  a.each do |sub_a|
    if sub_a.class == Array
      dim = get_dimension(sub_a)
      result = dim + 1 if dim + 1 > result
    end
  end
  return result
end

编辑:和红宝石是一个伟大的语言,并允许你做一些花哨的东西,你也可以让get_dimension阵列的方法:

and as ruby is a great language and allows you to do some fancy stuff you can also make get_dimension a method of Array:

 class Array
   def get_dimension
   ... # code from above slightly modified
   end
 end

这篇关于在红宝石多维数组的尺寸越来越的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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