Different working mechanism of reduce method in Ruby

a 夏天 提交于 2019-12-25 18:14:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!