+ 5
Challenge quiz explanation Ruby
How many times will the following loop execute? arr = [5, 6, 8, 3] arr.reverse! arr[1].times{puts "in a loop"} Answer is 8 I have no clue as to what just happened!
2 Respostas
+ 7
Let's break down the code:
arr = [5,6,8,3] creates an array with 4 elements.
arr.reverse! reverses the sequence of all of the elements in the list, making arr now equal to [3,8,6,5]
arr[1].times{puts "In a loop} will take the element at the index of 1 (because array indexes start from 0, the element at the index of one would be 8), and loop through whatever is in the curly brackets that number of times.
As a result, the code will print out 'in a loop' 8 times.
+ 3
That makes sense. Thank you Faisal.