From: Dante Regis Date: 2007-10-11T11:52:55+09:00 Subject: Re: |how do you know when to put a variable between pipes?| ------=_Part_41804_5582343.1192071163762 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline My example was wrong. Where it reads def my_each my_string = "" i = 0 while i <= self.size current_item = self[i] # ---- puts current_item my_string += " AND #{foo}" # ----- end self end it should read def my_each my_string = "" i = 0 while i <= self.size current_item = self[i] # ---- puts current_item my_string += " AND #{current_item}" # ----- end self end On 10/10/07, Dante Regis wrote: > > Another way to explain, complementing our friend Morton, is that when you > use a block, you are kind of inserting code inside another function. Let me > give you an example to help you understand. > > Let's take the "each" method of an array. You use this method when you > want to do something with every item inside the array. > > You could call something like: > my_string = "" > my_array.each do |foo| > puts foo > my_string += " AND #{foo}" > end > > Now, why did we place that |foo| on the block? Imagine that the "each" > method on the array is implemented like this: > > def each > i = 0 > while i <= self.size > current_item = self[i] > yield(current_item) > end > self > end > > Now notice two things: First, the "each" method itself has no parameters, > though it could have. They would have nothing to do with the pipes, though. > Second, look at the yield line. what yield do is to call the block that you > gave to this function. Since the yield is inside the while statement, it > will run as many times as there are items on your array. And, as i said it > is just like putting your piece of code inside the "each" (or any other) > method. It would be like you've written > > def my_each > my_string = "" > i = 0 > while i <= self.size > current_item = self[i] > # ---- > puts current_item > my_string += " AND #{foo}" > # ----- > end > self > end > > Now, the actual values that the block will take will clearly depend on the > function that you are using. SInce yield can pass as many parameter as it > wants (you could have something like yield a, b, c, d, e, ...) you should > see the documentation of the function to know which values are passed to the > block. > > It's obviously not a technical explanation, and some things are > intentionally wrong (the each method for array is implemented in C, for > instance), but maybe it helps you understand. > > Hope this helps > ------=_Part_41804_5582343.1192071163762--