尝试通过传递 lambda 对集合中的项目值求和。我认为这只是一些语法错误:
# inputs
setCosts = {["A"] => 3, ["B"] => 4, ["A", "B"] => 5 }
collectionOfSets= [[["A"], ["B"]], [["A"], ["A", "B"]]]
# method and lambda
getSetCost = ->(x) { setCosts[x] }
def SumEachBy(collec, &lamb) # stack trace starts here
sum = 0
collec.each { |x| sum += lamb(x) }
return sum
end
# process output
collecValues = Hash[collectionOfSets.map { |set| [set, SumEachBy(set, getSetCost)] }]
我越来越:
ArgumentError: wrong number of arguments (2 for 1)
我期望collecValues
成为:
{[["A"], ["B"]] => 7, [["A"], ["A", "B"]] => 8}
我的错误在哪里?
顺便说一句,如果在 Ruby 中有更好的方法可以做到这一点,也请告诉我。