Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHyunsoo Choi
1,255 PointsHow did the variable |item| printed out number from 0 to 4?
I mean we didn't set the "item" variable to contain any digits. Why did Ruby print out 0 to 4?
3 Answers
Marcus Parsons
15,719 PointsHi Hyunsoo,
Using the times
function, you don't have to set the argument you use to any value because the argument automatically contains each iteration of the loop. That means that each time that times
runs, it puts the value it is currently on into item
which can then be used inside of the loop.
Kantimoy Sur
iOS Development with Swift Techdegree Student 22,499 PointsI know its really late to reply at this point of time and you might know the answer as well but if you didn't then hope this helps. Actually this loop is running like other "array.each" loop ( i.e. using "each" keyword on any array ) . What happens is behind the code is every time the loop runs the LOCAL VARIABLE is set to its index value. And it starts always from 0 then 1, 2, 3 .. and so on. So when you do 5.each even if you don't use " variable " , the loop is already using a local variable (behind the scene) but when you yourself give a local variable , in this case it is |item| , then that " |item| " is given value of that index every time. So here it becomes 0, 1, 2 ... and continues until 4 because "5" becomes out of index ( in array ). It is just that if you want to access the index variable you need some random variable of your own.
Summarizing ---- ( just to explain you) the code might work in similar fashion if not exactly the same --- when you don't give a local variable then index =0 then index = 1, 2, 3 ... and the code uses index behind the scene BUT when you give a local variable (lets use variable "local" here) local = index ( so here local is 0, 1, 2, 3 ... )
I tried to explain you in much details as possible and hope you understand now.
Jitli Gan
2,668 PointsCan someone explain this clearer? I don't really get this.