试图通过应用于对象的一系列函数来理解闭包

时间:2014-08-20 10:25:52

标签: ruby closures

我有三个功能(它们可以工作),我认为可以使用闭包来完成。这是我的工作:

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
 .....

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

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

1 个答案:

答案 0 :(得分:4)

您可以将方法名称作为符号传递,然后使用.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)