开发者

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

开发者 https://www.devze.com 2023-04-13 05:38 出处:网络
In Ruby, is there a simple way to multiply every element in an n-dimensional array by a single number?

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_b开发者_开发技巧y function to distinguish it from *, which appears to concatenate multiple copies of the array, which is unfortunately not what I need).

Thanks!


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


How about using Matrix class from 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]]


Facets, as usual, has 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号