Challenge quiz explanation Ruby | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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!

15th Jan 2018, 4:50 AM
Jeffrey Koh
Jeffrey Koh - avatar
2 Answers
+ 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.
15th Jan 2018, 4:56 AM
Faisal
Faisal - avatar
+ 3
That makes sense. Thank you Faisal.
15th Jan 2018, 5:05 AM
Jeffrey Koh
Jeffrey Koh - avatar