本文介绍了Ruby 注入初始值是一个哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我为什么会出现以下情况:
Can any one tell me why the following:
['a', 'b'].inject({}) {|m,e| m[e] = e }
抛出错误:
IndexError: string not matched
from (irb):11:in `[]='
from (irb):11:in `block in irb_binding'
from (irb):11:in `each'
from (irb):11:in `inject'
from (irb):11
from C:/Ruby192/bin/irb:12:in `<main>'
而以下有效?
a = {}
a["str"] = "str"
推荐答案
你的区块需要返回累积的哈希值:
Your block needs to return the accumulating hash:
['a', 'b'].inject({}) {|m,e| m[e] = e; m }
相反,它在第一次传递后返回字符串 'a',在下一次传递中它变成 m
并且您最终调用字符串的 []=
方法.
Instead, it's returning the string 'a' after the first pass, which becomes m
in the next pass and you end up calling the string's []=
method.
这篇关于Ruby 注入初始值是一个哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!