带有索引的Ruby`his_with_object`
我想用index
做a.each_with_object
带有index
a.each_with_object
,其方式比这更好:
a = %w[abc] a.each.with_index.each_with_object({}) { |arr, hash| v,i = arr puts "i is: #{i}, v is #{v}" } i is: 0, v is a i is: 1, v is b i is: 2, v is c => {}
有没有办法在没有v,i = arr
情况下做到这一点?
代替
|arr, hash|
你可以做
|(v, i), hash|
在您的示例中.each.with_index
是多余的。 我找到了这个解决方案
['a', 'b', 'c'].each_with_object({}).with_index do |(el, acc), index| acc[index] = el end # => {0=>"a", 1=>"b", 2=>"c"}
你可以替换你的最后一行
puts "i is: %d, v is %s" % arr.reverse
但是,正如@sawa建议的那样,消除数组参数的歧义就是要做的事情。 我只是提到这个东西要存放一天。