Multiply each element of an n-dimensional array by a number in Ruby

In Ruby, is there an easy way to multiply each element in an n-dimensional array by one number?

Thus: [1,2,3,4,5].multiplied_by 2 == [2,4,6,8,10]

and [[1,2,3],[1,2,3]].multiplied_by 2 == [[2,4,6],[2,4,6]] ?

(Obviously, I made up the multiplied_by function to distinguish it from * , which seems to combine multiple copies of the array, which, unfortunately, is not what I need).

Thanks!

+4
source share
3 answers

The long format equivalent of this:

 [ 1, 2, 3, 4, 5 ].collect { |n| n * 2 } 

This is not so difficult. You can always make your multiply_by method:

 class Array def multiply_by(x) collect { |n| n * x } end end 

If you want this to be multiple recursive, you need to handle this as a special case:

 class Array def multiply_by(x) collect do |v| case(v) when Array # If this item in the Array is an Array, # then apply the same method to it. v.multiply_by(x) else v * x end end end end 
+6
source

How about using the Matrix class from the ruby ​​standard library?

 irb(main):001:0> require 'matrix' => true irb(main):002:0> m = Matrix[[1,2,3],[1,2,3]] => Matrix[[1, 2, 3], [1, 2, 3]] irb(main):003:0> m*2 => Matrix[[2, 4, 6], [2, 4, 6]] irb(main):004:0> (m*3).to_a => [[3, 6, 9], [3, 6, 9]] 
+3
source

Borders, as usual, have some neat ideas:

 >> require 'facets' >> [1, 2, 3].ewise * 2 => [2, 4, 6] >> [[1, 2], [3, 4]].map { |xs| xs.ewise * 2 } => [[2, 4], [6, 8]] 

http://rubyworks.github.com/facets/doc/api/core/Enumerable.html

+1
source

All Articles