On Sat, Mar 17, 2007 at 07:58:15AM +0900, Corey Konrad wrote:
> Chad Perrin wrote:
> > On Sat, Mar 17, 2007 at 07:36:21AM +0900, Corey Konrad wrote:
> >> >> why is that, cant yield be used with arguments?
> >> 
> >> oh ok, my understanding for some reason was that the method was going to 
> >> remmeber that i set arg to "ball" so that when i used printer with the 
> >> block that "ball" would still be in arg. So is that why it isnt working, 
> >> is because when i call the printer method the second time the value 
> >> stored in arg is destroyed?
> > 
> > I'm just guessing here, but . . .
> > 
> > It looks like you're expecting something akin to class behavior from a
> > method.  Perhaps what you want to do is something more like this:
> > 
> > class Printer
> >   def initialize(arg)
> >     @arg = arg
> >   end
> > 
> >   def iterator_thingie
> >     yield @arg
> >   end
> > end
> > 
> > printer = Printer.new("ball")
> > printer.iterator_thingie {|word| puts word}
> > 
> > 
> > Then again, maybe that's not the kind of behavior you want.
> 
> what i am basically trying to understand is:
> 
> When i do printer("ball") i am putting the string ball in the arg 
> variable of the printer method.
> 
> When i call the printer method with the block afterwards what happened 
> to my string i stored in arg? Was it destroyed or when i called the 
> printer method for the second time did ruby create a whole new arg 
> variable with nothing in it and thats why the way i did it didnt work? 
> Do you know what i mean i am trying to understand why what i did didnt 
> work.

Methods are not persistent things -- they are actions taken by objects.
When you call a method that you define outside of any class, it's
actually a method of the Self object (basically, a method of your
program).  Because actions do not maintain state (data, variables, what
have you), variables within methods go away when the methods are not in
use.  A method is an ephemeral, fleeting thing.  It's an occurrence, in
a way, rather than a thing.

A method, in fact, is much like a function in that respect (if you're
familiar with functions from other languages).  You put something in,
you get something out.

Blocks can be used to maintain state, but to do so you need to assign
them as objects to some kind of name/variable/thing that is outside of a
method.  That, of course, is because a block returned from a method and
stuck in a variable is basically the same as a closure in any other
language (that supports closures).

Hopefully that helps clear things up for you, and give you a glimpse of
other, sorta related topics in the language.

-- 
CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ]
"The measure on a man's real character is what he would do
if he knew he would never be found out." - Thomas McCauley