Ruby inject with initial being a hash

后端 未结 3 573
囚心锁ツ
囚心锁ツ 2020-12-12 15:19

Can any one tell me why the following:

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

throws the error:

IndexError: string no         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 15:25

    Your block needs to return the accumulating hash:

    ['a', 'b'].inject({}) {|m,e| m[e] = e; 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.

提交回复
热议问题