ruby 注入方法没有做我认为应该做的事情 [英] ruby inject method not doing what I thought it should be doing

查看:50
本文介绍了ruby 注入方法没有做我认为应该做的事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道为什么会失败吗?

Does anyone have any idea why this is failing?

ree-1.8.7-2011.03 :008 > 3.times.inject({}) {|result, el| result[el.months.ago.strftime("%B")] = "blah"}
IndexError: string not matched
  from (irb):8:in `[]='
  from (irb):8
  from (irb):8:in `inject'
  from (irb):8:in `each'
  from (irb):8:in `times'
  from (irb):8:in `each'
  from (irb):8:in `

推荐答案

inject 将块的返回值作为 result 提供给下一次迭代,但哈希分配返回分配的内容.从块中返回 result:

inject feeds the block's return value into the next iteration as result but Hash assignment returns what was assigned. Return result from the block:

3.times.inject({}) {|result, el| result[el.months.ago.strftime("%B")] = "blah"; result }

或使用each_with_object 因为你并没有真正注入:

or use each_with_object since you're not really injecting:

3.times.each_with_object({}) {|el, result| result[el.months.ago.strftime("%B")] = "blah" }

这篇关于ruby 注入方法没有做我认为应该做的事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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