Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
假设我有一个这样的数组:
[1,2,3,4,5,6,7]
我如何将除第一个数组之外的所有其他数字乘以 2,所以我的新数组看起来像这样
[1,4,3,8,5,12,7]
您可以使用map和with_index:
map
with_index
[1,2,3,4,5,6,7].map.with_index{|v,i| i % 2 == 0 ? v : v * 2 } # => [1, 4, 3, 8, 5, 12, 7]
[1,2,3,4,5,6,7].each_slice(2).flat_map{|k, l| [k, *(l * 2 if l)]} # => [1, 4, 3, 8, 5, 12, 7]