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 trialAnas Rida
8,183 Pointswhat does "do" mean in this example
I was wondering what the "do |file|" means in this example. File.open(parameters) opens the file with the given parameters. But then where did 'file' come from? I thought do || is for setting parameters like in my_array.each do |x|, here it would iterate over the array. But I can't seem to grasp in this example what it means.
Thanks in advance
1 Answer
Ari Misha
19,323 PointsHiya there! do is the starting point of the code block. Its kinda like {} or (). "do" represents the starting point of the code block and "end" is the end of the block. In Ruby, code block can be passed to almost anything. It executes everything in the code block , if passed any local variable or alias , Ruby keep tracks of values by assigning 'em to the local variable temporarily.
Now regarding the example code, the file was opened in the "write" mode and file local variable was assigned to the file that was opened. So yeah all ya have to do is call file in order to refer to the File outside the code block. I hope it helped. (:
Maximiliane Quel
Courses Plus Student 55,489 PointsMaximiliane Quel
Courses Plus Student 55,489 PointsHi Anas,
you are not giving a lot of information on what you are seeing. We cannot see your code or where you found it. I will nevertheless try and answer your questions in general. In ruby you open blocks by either using {} or the keywords do and end. In between || you can set a temporary variable that will be passed to the block. As you correctly state the |x/ is there to temporarily store each item in an array while you iterate over it and do something with that x before moving on the the next value of x until all items in the array have been passed to the x and used in the block. So do pretty much always opens the block and instead of file you could also use another word that stands in for your temporary variable. Usually you want it to be some descriptive word so that you remember what the variable stands for.
I hope this helps.