Ruby: inject issue when turning array into hash

后端 未结 4 1104
甜味超标
甜味超标 2020-12-11 02:18
a = [[1, \'a\'],[2, \'b\'],[3, \'c\'], [4, \'d\']]
a.inject({}) {|r, val| r[val[0]] = val[1]}

When I run this, I get an index error

When I change the b

4条回答
  •  庸人自扰
    2020-12-11 02:40

    The first block returns the result of the assignment back into the inject, the second returns the hash, so it actually works.

    A lot of people consider this usage of inject an anti-pattern; consider each_with_object instead.

提交回复
热议问题