问题
So I recently noticed that the order of you put in parameters in ruby's reduce method influenced the results.
a = ["1", "2", "3"]
a.reduce {|val, con| val + con}
a = ["123"]
However
a.reduce {|val, con| con + val}
a = ["321"]
I think it only matters how you give order to |val, con| pair, which means if con shows at the latter position, the result of every step is always gonna be stored in con. And these two should yield the same result. But obviously not here.
Anyone could provide some tips? Thanks. Any explanation of how these two methods are implemented in Ruby would hugely help.
回答1:
Print each step to see what's going on.
a = %w{1 2 3}
a.reduce {|memo, obj|
puts "memo is #{memo} and obj is #{obj}"
puts "new memo is #{memo + obj}", "="*23
memo + obj
}
#memo is 1 and obj is 2
#new memo is 12
#=======================
#memo is 12 and obj is 3
#new memo is 123
#=======================
a.reduce {|memo, obj|
puts "memo is #{memo} and obj is #{obj}"
puts "new memo is #{obj + memo}", "="*23
obj + memo
}
#memo is 1 and obj is 2
#new memo is 21
#=======================
#memo is 21 and obj is 3
#new memo is 321
#=======================
回答2:
The first parameter of the block is the memo, the object on which is build the solution, the latter is the "current item" of your collection. So, in the first example you are concatenating the items after your memo, in the second example before the memo. Both the ways are legits. In the end it depends what you have to do.
来源:https://stackoverflow.com/questions/46306085/different-working-mechanism-of-reduce-method-in-ruby