Ruby中reduce方法的不同工作机制 [英] Different working mechanism of reduce method in Ruby

查看:51
本文介绍了Ruby中reduce方法的不同工作机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我最近注意到你在 ruby​​ 的 reduce 方法中放入参数的顺序影响了结果.

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"]

不过

a.reduce {|val, con| con + val}
a = ["321"]

我认为重要的是你如何命令|val, con|对,这意味着如果 con 显示在后一个位置,则每一步的结果总是会存储在 con 中.这两个应该产生相同的结果.但显然不是这里.

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.

谁能提供一些建议?谢谢.任何关于如何在 Ruby 中实现这两种方法的解释都会有很大帮助.

Anyone could provide some tips? Thanks. Any explanation of how these two methods are implemented in Ruby would hugely help.

推荐答案

打印每一步,看看发生了什么.

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
#=======================

这篇关于Ruby中reduce方法的不同工作机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆