How to Use the "each" Method in Ruby on Rails2:29 with Jason Seifer
The "each" method in Ruby on Rails allows you to iterate over different objects inside an array-like structure. It's an important part of development in Ruby, and Treehouse's Ruby teacher, Jason, explains how to use it effectively in this Treehouse Quick Tip!
This video doesn't have any notes.
[? Music ?] [Treehouse presents] 0:00 [Quick Tips] [How to Use the "each" Method in Ruby on Rails with Jason Seifer] 0:02 Hi, I'm Jason. 0:05 In this Treehouse Quick Tip, we're going to talk about the each method in Ruby. 0:07 The each method is part of the enumerable mixin. 0:11 The each method lets you iterate over different objects 0:14 inside of an array-like structure. 0:18 The method takes a block which specifies 0:20 what will happen on each successive iteration in the loop. 0:23 Here's how the each method looks. 0:27 Right now, I'm in an irb session. 0:30 Let me create an array of a few different things. 0:33 I have an array with 3 different items in it right now: 0:40 dog, cat, and frog. 0:43 If I wanted to go through and print out each of the different items 0:46 in the array, it would be really easy to do using the each method. 0:49 Here's what it would look like. 0:54 Now, in order to call the each method, 1:07 first, I type out the name of the object I want to iterate over, 1:09 which in this case is the array variable. 1:13 Then I type a period, which calls a method, 1:16 and then the name of the method I want to call, 1:20 in this case, each. 1:23 From there, type out a space and the word do. 1:26 Do tells the Ruby interpreter 1:31 that we're going to expect a block. 1:33 Then I type another space, 1:36 and I put the word item inside of 2 vertical pipes. 1:39 Anything in between these pipes is an argument to the block 1:43 which was specified by the do keyword, 1:47 and these arguments are going to be available 1:50 inside of the block. 1:52 From there, I press enter, and I type out what I want to happen 1:55 to the item. 1:58 In this case, I'm only printing out what the item is. 2:00 You don't need to worry about modifying the original items 2:04 inside the block, because only a copy is sent in, 2:07 and anything that you do won't affect the original item in the array. 2:11 That was 1 quick use of the each method. 2:17 You could have as much code as you want inside of the block. 2:20 Just make sure to keep it readable. 2:24
You need to sign up for Treehouse in order to download course files.Sign up