From: 7stud -- Date: 2007-10-11T11:46:21+09:00 Subject: Re: |how do you know when to put a variable between pipes?| A Love of Surf wrote: > Hi i am at about page fifty in the pickaxe book, and i have a > question. I see a lot of examples of a block that starts with > |SomeVar| > and I dont really understand how you know when you can do > this Whenever a method specified to the left of the block has a yield statement in its definition, the method is going to pass a value to the block. For example: def my_method yield 10 end my_method {|num| puts num * 2} #20 How do you know if one of ruby's methods has a yield statement in its definition? You could look at the source code, but for now just remember that when the book says that a method is an iterator, then the method is going to send one or more values to a block. Or, if the book introduces a method and also uses a block after the method call, then you know the definition of the method has a yield statement in it, which just means it is going to send one or more values to the block. What you should be trying to figure out is: 1) what values the method call sends to the block 2) what the return value of method call is The most common iterator is 'each'. When called on an array, each sends each element of the array to the block one at a time. You should make frequent use of the reference section in the back of the book to look up methods and read about what values they send to a block, and what the return value of the method call is. > or what the value will be that is passed to the variable. It depends on how the method you call is defined: def my_method yield 20 yield 30 end my_method {|num| puts num * 2} #40 60 > What > is the name of this construct or the var that goes in pipes? The construct is exactly like a method definition, and it is called a "block". The thing in the pipes is the same thing as a parameter variable in a method definition. You are calling a method: my_method with a block specified on the right: {|num| puts num * 2} The block is just like a method, but it doesn't have a name. Backing up a little, you can define methods that call each other like this: def my_method calculate(10) end def calculate(num) puts num * 2 end my_method #20 The same thing is happening with a method call that is followed by a block: you are calling a method that sends values to another method(the block). -- Posted via http://www.ruby-forum.com/.