Here are a few methods to extend the Array class in Ruby. It will let you
sum up Arrays, find how many level of Array are nested into each other, and
divide all the elements contained in an Array and in all the nested Arrays it
might contain.
- !ruby
# A new method to Array to sum elements between two arrays in a new array.
# It works recursively with arrays of arrays
class Array
def add(y)
return self if y.empty?
return y if self.empty?
if self.deepness == 1 and y.deepness == 1
a_sum = self.zip(y.flatten).map{|a,b| a.to_f+b.to_f}
return a_sum
else
if y0.is_a? Array and self0.is_a? Array
res = Array.new
y.each_index do |i|
res.push selfi.add yi
end
return res
end
end
end
# Return the deepness of an Array, ie how many Arrays does it
# recursively contains ? Note that the computation is only performed on the first item of the array.
def deepness
a = self.collect0
return 1 if not a.is_a? Array
return 1 + a.deepness if a.is_a? Array
end
# Division applied recursively on every element
def div(n)
a =
self.each do |s|
if not s.is_a? Array
a.push (s.to_f/n.to_f)
else
a.push s.div(n)
end
end
return a
end
end