我想这样做a.each_with_object有index,在比这更好的办法:
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)
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)