我有一个数组。我需要对每个元素执行不同的计算。我以为我可以做以下事情:
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
适当的乘数值连接输入数组中的元素。另外,通过从执行乘法的逻辑(inmultiply_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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句