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.
Here is an example:
For [[1, 2],[3,4],[5,6]] the dimension should be 2.
For [[[1,2],[2,3]],[[3,4],[5]]], the dimension should be 3.
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 that by dimension you mean “the deepest nested level of arrays” this should do the trick:
EDIT: 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: