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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With