我有一个数组。我需要对每个元素执行不同的计算。我想我可以做类似下面的事情:
def calc(a, b, c)
arr = [a, b, c]
arr.map { |i| (i[0] * 600), (i[1] * 800), (i[2] * 1000) }
end
calc(5, 8, 15)
但这行不通。如何对单个数组的每个元素执行不同的计算?
最佳答案
以下是一些可能有用的其他实现。通过将乘数放入数组中,我们可以使用 zip
将输入数组中的元素与适当的乘数连接起来。此外,通过从执行乘法的逻辑中删除乘数值(在 multiply_arrays
和 transform_arrays
中),这使得进一步抽象逻辑变得简单。
#!/usr/bin/env ruby
VALUES = [1, 1, 1]
MULTIPLIERS = [600, 800, 1000]
def transform(*values)
values.zip(MULTIPLIERS).map { |x, y| x * y }
end
def multiply_arrays(array1, array2)
array1.zip(array2).map { |n1, n2| n1 * n2 }
end
def transform_arrays(array1, array2, method_name)
array1.zip(array2).map { |n1, n2| n1.public_send(method_name, n2) }
end
p transform(*VALUES) # [600, 800, 1000]
p multiply_arrays(VALUES, MULTIPLIERS) # [600, 800, 1000]
p transform_arrays(VALUES, MULTIPLIERS, :*) # [600, 800, 1000]
如果计算需要有很大的不同(不同的运算符、值、更复杂的逻辑),我会考虑使用 lambda 数组:
def transform_with_lambdas(values, transforms)
values.zip(transforms).map do |value, transform|
transform.(value)
end
end
TRANSFORMS = [
->(x) { x * 600 },
->(x) { x + 100 },
->(x) { x / 3.0 },
]
p transform_with_lambdas(VALUES, TRANSFORMS) # [600, 101, 0.3333333333333333]
关于arrays - 对数组的每个元素执行不同的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37361187/