Ruby::Array
There are some cool aspects about Ruby, one of them is the ability to modify classes at rumtime. There also are bad aspects to it, but this is another story.
The Array class lacks a few methods that I needed a while ago. Here are a few methods that I wrote to extend this class.
Sum up arrays
class Array #A new method to Array to sum elements between two arrays # It works recursively with arrays of arrays 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_sumelse if y[0].is_a? Array and self[0].is_a? Array res = Array.new y.each_index do |i| res.push self[i].add y[i] end return res end end end end
Example: @
@a1 = [1,2,3]
a2 = [4,5,6]
a1.add(a2) => [5,7,9]
Nested arrays
Find out how many arrays are nested into each other. We consider here that all the elements of the array have the same “deepness”, and only take the first item.
# Return the deepness of an Array, aka how many Arrays does it
# recursively contains ? Note that this is based on the first item only
def deepness
a = self.collect[0]
return 1 if not a.is_a? Array
return 1 + a.deepness if a.is_a? Array
end
Example:
a1 = []
a2 = []
a3 = []
a1.push(a2.push(a3))
a1.deepness => 3
Recursive division
Divide all the elements contained in an Array and in all the nested Arrays it might contain by a given number.
# Division applied recursively on every elements
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
Example:
a1 = [2,4,6]
@a1.div(2) => [1,2,3]