2017-02-25 30 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 }