在 Ruby 中,是否有一种简单的方法可以将 n 维数组中的每个元素乘以一个数字?
这样:
[1,2,3,4,5].multiplied_by 2 == [2,4,6,8,10]
和[[1,2,3],[1,2,3]].multiplied_by 2 == [[2,4,6],[2,4,6]]
?
(很明显,我编写了 multiplied_by
函数以区别于 *
,它似乎连接了数组的多个副本,不幸的是这不是我需要的)。
谢谢!
最佳答案
它的长格式等价物是:
[ 1, 2, 3, 4, 5 ].collect { |n| n * 2 }
其实并没有那么复杂。你总是可以使你的 multiply_by
方法:
class Array
def multiply_by(x)
collect { |n| n * x }
end
end
如果你想让它递归地相乘,你需要把它作为一种特殊情况来处理:
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
关于ruby - 将n维数组的每个元素乘以Ruby中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7769136/