![](/img/trans.png)
[英]Add elements of an array to a specific index of each array within an array of arrays
[英]How to get specific value within an array of arrays
我有一個數組(外部數組),包含三個數組(內部數組),每個數組有三個元素。
array = [[a, b, c], [d, e, f], [g, h, i]]
我想使用外部數組的索引選擇特定的內部數組,然后根據其索引選擇所選內部數組中的值。 這是我嘗試過的:
array.each_index{|i| puts "letter: #{array[i[3]]} " }
我希望能給我以下輸出
letter: c letter: f letter: i
但相反,我得到了
letter: [[a, b, c], [d, e, f], [g, h, i]]
我也試過了
array.each_index{|i| puts "letter: #{array[i][3]} " }
但我得到了相同的結果。 請任何建議非常感謝。 我需要一個簡單的解釋。
each_index
是一個Enumerable,它遍歷所有索引並對每個索引執行操作。 當它完成后,它將返回您的原始集合,因為它不是它的工作來改變它。 如果你想通過puts
/ print
在屏幕上輸出內容,那么each_index
就可以了。
如果要通過瀏覽原始集合的所有元素來創建新集合,則應使用map 。
例如
array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
new_array = array.map {|el| el[2]}
=> ["c", "f", "i"]
array.map遍歷數組的元素,因此在每個步驟| el |中都是如此 是一個元素,而不是一個索引,如:第一次迭代中的['a', 'b', 'c']
,第二次迭代中的['d', 'e', 'f']
,依此類推。 ..
只是指出這一點,因為我不知道你想要做的目標是什么。
像這樣做:
array.each_index{|i| puts "letter: #{array[i][2]} " }
因為你想要索引2處的字母,而不是3。
數組也應該像這樣定義:
array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
您可以像這樣使用map
:
a = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
a.map(&:last)
# => ["c", "f", "i"]
或者,如果您真的想要看跌期權而不是收集的價值:
a.each {|v| puts "letter: #{v.last}"}
如果你想要做更多Matrix-y的東西,你也可以使用Ruby的Matrix
類:
require 'matrix'
m = Matrix[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
last_column = m.column_vectors.last
# => Vector["c", "f", "i"]
您現在可以使用last_column
上的任何Vector
方法,包括to_a
,這將使您回到熟悉的領域,並使用最后一列的值。
ruby中的數組從0開始索引,而不是從1索引。所以:
array.each_index{|i| puts "letter: #{array[i][2]} " }
應該給你你想要的東西。
您也可以嘗試下面的內容:
p RUBY_VERSION
arr = [[1,2,3],[4,5,6],[11,12,13]]
arr.each{|x| p x; x.each_index{|i| p "Digit :: #{x[i]}" if i == 2} }
輸出:
"2.0.0"
[1, 2, 3]
"Digit :: 3"
[4, 5, 6]
"Digit :: 6"
[11, 12, 13]
"Digit :: 13
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.