2017-02-25 31 views
0

數據結構是我的弱點,我希望對此有更深入的理解。希望在此澄清一些情況。ruby​​中的數組內的多維數組數組

sandwiches = [["cheese", "ham"], ["avocado", "bacon"], ["tomato","pesto","cheese","mayo"], ["egg"], ["turkey", "ketchup", "mustard"]] 

如果我錯了,請糾正我。謝謝!

裏面的三明治,有1個陣列。 在子三明治數組中,有5個數組。

但我堅持瞭解三明治數組和子三明治數組中有多少元素。

回答

0

你有1major具有5種元素[0,1,2,3,4]

元素在位置0陣列是另一陣列2層的元件

元位置1處的是另一個陣列具有2個元素太

元在2位是具有4個元件

元在位置3另一陣列與1個元件另一個陣列

元在位置4是另一陣列3層的元件

PS:ü可以考慮用逗號(,)

即分離的每個元件的位置處:[fisrt_element,second_element,[fist_element_of_this_arry,second_element_of_this_arry],fourth_element]

所以陣列上方是具有4個元件和元件3的一個主要陣列是具有兩個元素的數組:[0,1,[0,1],3]

記住,陣列位置贈品從0開始

2

三明治數組包含5個元素(以及這些元素也是一個數組):

sandwiches = [ 
["cheese", "ham"], #first element of sandwiches -> an array with 2 elements (cheese and ham) 
["avocado", "bacon"], #second element of sandwiches, an array with 2 elements (avocado and bacon) 
["tomato","pesto","cheese","mayo"], # third element of sandwiches, an array with 4 elements (tomato, pesto, cheese and mayo) 
["egg"], # fourth element of sandwiches, an array with one element (egg) 
["turkey", "ketchup", "mustard"] # fifth element of sandwiches, an array with 3 elements (turkey, ketchup and mustard) 
] 
3

您可以使用Ruby自己找出答案,這樣的問題:

sandwiches.map(&:length) 
#=> [2, 2, 4, 1, 3] 

這給了你每個數組的嵌套長度爲sandwiches

請注意.map(&:length)是短版.map { |x| x.length }