gpt4 book ai didi

ruby - 尝试通过应用于对象的函数总和来理解闭包

转载 作者:数据小太阳 更新时间:2023-10-29 08:37:47 25 4
gpt4 key购买 nike

我有三个函数(它们有效),我认为可以使用闭包来完成。这是我所做的:

def sum_with_first_function (parent)
total=0
parent.items.each do |item|
total+= BuisnessLogic.new(item).first_function
end
total
end

def sum_with_second_function (parent)
total=0
parent.items.each do |item|
total+= BuisnessLogic.new(item).second_function
end
total
end

def sum_with_third_function
.....

如您所见,它所做的只是具有第一、第二或第三功能的项目的总和。

是否可以修改此代码以使用闭包并将函数用作参数?

最佳答案

您可以将方法名称作为符号传递,然后使用 .send 方法调用它。

def sum_with(parent, method)
parent.items.inject(0){ |sum, item| sum + BuisnessLogic.new(item).send method }
end

# usage
sum_with(parent, :first_method)
sum_with(parent, :second_method)

关于ruby - 尝试通过应用于对象的函数总和来理解闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25402377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com