假设我有许多相同大小的数组,包含一些元素,例如其中一个可能是:
arr = ['a', 'b', 'c', 'd']
我想在每个元素上调用一个不同的函数,具体取决于它的索引,所以我可以这样做:
arr.each_with_index do do |el, idx|
case idx
when 0
functionA el
when 1
functionB el
# and so on..
end
end
Run Code Online (Sandbox Code Playgroud)
有没有更短的方法来做到这一点?类似于分配给变量的东西:
a, b, c, d = arr
Run Code Online (Sandbox Code Playgroud)
但我想调用函数,而不是做任务.
您可以准备一组funcs然后将两者拼接在一起.像这样的东西:
# stabby lambdas instead of methods. Because methods aren't objects.
func_a = ->(el) { puts "1 for #{el}" }
func_b = ->(el) { puts "2 for #{el}" }
func_c = ->(el) { puts "3 for #{el}" }
arr = ['a', 'b', 'c', 'd']
funcs = [func_a, func_b, func_c, func_a] # reusing func_a
arr.zip(funcs) {|a, f| f.call(a) }
# >> 1 for a
# >> 2 for b
# >> 3 for c
# >> 1 for d
Run Code Online (Sandbox Code Playgroud)
这是一个如何将方法转换为proc对象的技巧,以便您可以将它们放在数组中并稍后调用.但是要小心,与常规方法相比,这些调用更昂贵(无论如何,除非你已经挤出CPU的周期)
def func_a el; puts "1 for #{el}"; end
def func_b el; puts "2 for #{el}"; end
def func_c el; puts "3 for #{el}"; end
arr = ['a', 'b', 'c', 'd']
funcs = [method(:func_a), method(:func_b), method(:func_c), method(:func_a)] # reusing func_a
arr.zip(funcs) {|a, f| f.call(a) }
# >> 1 for a
# >> 2 for b
# >> 3 for c
# >> 1 for d
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
103 次 |
最近记录: |