0

Data Structure is my weakness and I want to get a deeper understanding on it. would appreciate some clarification here.

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

Please correct me if I am wrong. thanks!

Inside sandwiches, there is 1 array. Inside the sub-sandwiches array, there are 5 arrays.

But I'm stuck on understanding how many elements there are in the sandwiches array and the sub sandwiches array.

3 Answers 3

3

You can use Ruby itself to figure out the answer to such questions:

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

This gives you the length of each array nested in sandwiches.

Note that .map(&:length) is the short version of .map { |x| x.length }.

Sign up to request clarification or add additional context in comments.

Comments

2

The sandwiches array contains 5 elements (and each of these elements is also an array):

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)
]

Comments

0

you have 1major array with 5 elements [0,1,2,3,4]

Element at position 0 is another array with 2 elements

Element at position 1 is another array with 2 elements too

Element at position 2 is another array with 4 elements

Element at position 3 is another array with 1 element

Element at position 4 is another array with 3 elements

Ps: u can consider a position each element separated by comas (,)

i.e: [ fisrt_element, second_element, [fist_element_of_this_arry, second_element_of_this_arry], fourth_element]

so the array above is one major array with 4 elements and element 3 is an array with two elements: [0,1, [ 0,1], 3]

remember that array position aways begin from 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.