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.
Simple, object-oriented solution.
class Array
def depth
map {|element| element.depth + 1 }.max
end
end
class Object
def depth
0
end
end
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:
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
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:
class Array
def get_dimension
... # code from above slightly modified
end
end
in the simplest case
depth = Proc.new do |array|
depth = 1
while Array === array.first do
array = array.first
depth += 1
end
depth
end
array = [[[1,2],[2,3]],[[3,4],[5]]]
depth.call(array)
#=> 3
Or this tiny recursive method
def depth(array, depth=1)
array = array.send(:first)
Array === array ? depth(array, depth+1) : depth
end
array = [[[1,2],[2,3]],[[3,4],[5]]]
depth(array)
#=> 3
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