带有索引的Ruby`very_with_object`

Abd*_*bdo 28 ruby

我想这样做a.each_with_objectindex,在比这更好的办法:

a = %w[a b c]
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
=> {}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点没有v,i = arr

saw*_*awa 46

代替

|arr, hash|
Run Code Online (Sandbox Code Playgroud)

你可以做

|(v, i), hash|
Run Code Online (Sandbox Code Playgroud)

  • 这是错误的,@ka8725 下面的答案是正确的,它应该是 |(v, hash), i|,而不是 |(v, i), hash| (3认同)

ka8*_*725 42

在你的例子.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"}
Run Code Online (Sandbox Code Playgroud)