Trying to sum values of items in a collection of sets by passing a lambda. I'm thinking this is just some syntax error:
尝试通过传递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)] }]
I'm getting:
ArgumentError: wrong number of arguments (2 for 1)
I'm expecting collecValues
to be:
我期待collecValues是:
{[["A"], ["B"]] => 7, [["A"], ["A", "B"]] => 8}
Where is my error?
我的错误在哪里?
By the way, if there's a better way to do this in Ruby, please let me know that too.
顺便说一句,如果有更好的方法在Ruby中这样做,请告诉我。
2 个解决方案
#1
4
Adding &
before the last parameter means it would be bound to a block used along with method invocation, and you want to pass lambda as a param.
在最后一个参数之前添加&表示它将绑定到与方法调用一起使用的块,并且您希望将lambda作为参数传递。
Just remove it (def SumEachBy(collec, lamb)
) and enjoy your lambda :)
只需删除它(def SumEachBy(collec,lamb))并享受你的lambda :)
#2
-1
I Dont know about the hole code but u can update the sum part by using inject:
我不知道孔代码,但你可以使用inject更新sum部分:
def SumEachBy(collec, lamb)
collection.inject(0) { |sum, value| sum += value }
end
I could understand your code at all, what do u want to achieve here?
我完全可以理解你的代码,你想在这里实现什么?
I edit the answer following Anton suggestion. =)
我根据安东的建议编辑答案。 =)
#1
4
Adding &
before the last parameter means it would be bound to a block used along with method invocation, and you want to pass lambda as a param.
在最后一个参数之前添加&表示它将绑定到与方法调用一起使用的块,并且您希望将lambda作为参数传递。
Just remove it (def SumEachBy(collec, lamb)
) and enjoy your lambda :)
只需删除它(def SumEachBy(collec,lamb))并享受你的lambda :)
#2
-1
I Dont know about the hole code but u can update the sum part by using inject:
我不知道孔代码,但你可以使用inject更新sum部分:
def SumEachBy(collec, lamb)
collection.inject(0) { |sum, value| sum += value }
end
I could understand your code at all, what do u want to achieve here?
我完全可以理解你的代码,你想在这里实现什么?
I edit the answer following Anton suggestion. =)
我根据安东的建议编辑答案。 =)