谁能告诉我为什么会发生以下情况:

['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"

推荐答案

块需要返回累积哈希:

['a', 'b'].inject({}) {|m,e| m[e] = e; m }

相反,它在第一次传递后返回字符串"a",在下一次传递中变为m,最后调用字符串的[]=方法.

Ruby相关问答推荐

清理 jruby 中输入数据的编码错误

如何在 Ruby 中创建可调用属性

回声ABC | ruby -p -e "sub('a','A').sub('b', 'B')": 为什么不是 "ABc"?

如何判断一个对象在 Ruby 中是否可迭代?

Kernel#gets try 读取文件而不是标准输入

Ruby 中的 class() 与 type()

从href html标签中提取带有Ruby中nokogiri的链接(URL)?

我可以在 Ruby 中使用默认值创建一个数组吗?

如何找到安装 Ruby Gem 的路径(即 Gem.lib_path c.f. Gem.bin_path)

在包含任意数量的嵌套散列和数组的散列中查找键/值对

与 String 相比,在 Ruby 中使用 StringIO 有哪些优势?

rspec 是否有比 target.should < 6 更具体的东西?

了解 ruby​​-prof 输出

如何理解 strptime 与 strftime

如何使用 Ruby 运行命令五次?

Ruby 哈希白名单过滤器

不能在windows上安装thin

如何在 Ruby 中读取整个文件?

Array.empty 的相反方法是什么?或 [].empty?在Ruby中

传递哈希而不是方法参数