Reputation: 6189
I have a method that uses transpose, but I do not want to apply this operation if the array has less than 2 dimensions. I am wondering how I can do this in ruby.
so for an array like [1,2] -> it should say 1D
and for an array like [[1,2],[1,2]] it should say 2D
Any help appreciated,
Ted
Upvotes: 2
Views: 434
Reputation: 15478
Don't fear errors, just anticipate them:
a.transpose rescue a
Upvotes: 1
Reputation: 3776
module MultiDArray #this could be a subclass of Array
#if you can modify your callers
def self.transposable?(array)
array[0] && array[0][0]
end
def self.dimensions(array)
return 0 if array.nil?
return self.dimensions(array[0]) if array[0].is_a?(Array)
return 1
end
def self.dimension_to_s(array)
"#{dimensions(array)}D"
end
end
MultiDArray.transposable? #is probably what you're actually looking for.
This is presuming you're using normal ruby arrays and not Matrix
es.
You've probably got worse data model problems to deal with if the arrays aren't regular, so one of these two methodologies is probably sufficient.
Upvotes: 1
Reputation: 6967
How about
a.map{|e| e.is_a?(Array)}.uniq == [true] ? "#{e.size}D" : "1D"
Upvotes: 1
Reputation: 146053
Hmm, I might just try #transpose
and rescue IndexError, TypeError
, but another idea is:
x.map(&:class).uniq == [Array]
Upvotes: 1
Reputation: 37906
You could find it recursively:
def getDimension(array)
if array.first.is_a?(Array)
1 + getDimension(array.first)
else
1
end
end
I know it is a bit crude and there probably someone who is able to make it much nicer, but the general idea is clear.
Upvotes: 2
Reputation: 124632
Because Ruby arrays can hold anything this is fragile and a hack at best, but you could always just check to see if the nth element is an array, i.e.,
def is_2d(array)
array.first.is_a?(Array)
end
I really don't like this, so if there is something better just slap me or downvote me into oblivion.
Upvotes: 1