簡體   English   中英

在Ruby中的兩個單獨的數組中收集數組的所有元素和索引

[英]collect all elements and indices of an array in two separate arrays in Ruby

假設我有一個數組array = [1,2,3,4,5]

我想在2個單獨的數組中收集數組的所有元素和索引,例如

[[1,2,3,4,5], [0,1,2,3,4]]

如何使用單個Ruby collect語句執行此操作?

我正在嘗試使用此代碼

array.each_with_index.collect do |v,k|
  # code
end

要獲得所需的輸出,在代碼部分中應該做什么?

甚至更簡單:

[array, array.each_index.to_a]

我喜歡前一段時間發布的第一個答案。 不知道為什么那個家伙刪除了它。

array.each_with_index.collect { |value, index| [value,index] }.transpose

實際上,我正在使用自定義矢量類,在該類上調用了each_with_index方法。

這是一種簡單的方法:

array = [1,2,3,4,5]
indexes = *array.size.times
p [ array, indexes ]
# => [[1, 2, 3, 4, 5], [0, 1, 2, 3, 4]]

在repl.it上查看: https ://repl.it/FmWg

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM