Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Ruby, is there a simple way to multiply every element in an n-dimensional array by a single number?

Such that: [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 appears to concatenate multiple copies of the array, which is unfortunately not what I need).

Thanks!

like image 497
Russell Avatar asked Oct 14 '11 14:10

Russell


1 Answers

The long-form equivalent of this is:

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

It's not really that complicated. You could always make your multiply_by method:

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

If you want it to multiply recursively, you'll need to handle that 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
like image 120
tadman Avatar answered Sep 21 '22 23:09

tadman