Ruby: inject issue when turning array into hash

后端 未结 4 1105
甜味超标
甜味超标 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 03:04

    There is an easier way -

    a = [[1, 'a'],[2, 'b'],[3, 'c'], [4, 'd']]
    b = Hash[a] # {1=>"a", 2=>"b", 3=>"c", 4=>"d"}
    

    The reason the first method isn't working, is because inject uses the result of the block as the r in the next iteration. For the first iteration, r is set to the argument you pass to it, which in this case is {}.

提交回复
热议问题