From: Kyle Rawlins Date: 2002-06-13T03:10:39+09:00 Subject: Re: procs and blocks --FFoLq8A0u+X9iRU8 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Jun 13, 2002 at 02:40:01AM +0900, Evan Martin wrote: > latter sets $cb to a proc that wraps a block. Or are a proc and a block > the same thing? Someone can probably give you a more thorough answer, but my understanding = of it is that they are not the same thing. However, for your purposes (when y= ou are storing a callback) you can really only use a proc. The way I understand it is that a block is sort of a iconoclastic element of ruby in that it really isn't an object, and is only sort of an argument to whatever function it is given to. This is for efficiency reasons, which ma= kes sense considering that the main method of iterating over anything in ruby i= s to use a block. So it is much faster to use a combination of a block with yie= ld for your basic iterators. However, I don't think you can store a block by itself, you have to wrap a proc object around it. I believe that all proc objects (created the normal way) store blocks. So a block is just a proc that can be used directly without the overhead of creation, calling, etc. Also, for two of your solutions, the main difference for your purposes as f= ar as I can see is that you get different failure modes: (code not reproduced exactly, sorry) given def a(&p) $cb =3D p end def b $cb =3D Proc.new end irb(main):009:0> a # nil is silently stored to $cb: nil irb(main):032:0> $cb nil irb(main):033:0> b ArgumentError: tried to create Proc object without a block from (irb):29:in `new' from (irb):29:in `b' from (irb):33 It seems that for a formal proc parameter there is a default value of nil, resulting in a reference to nil rather than the ArgumentError one might exp= ect when it isn't given. Thinking about it, you might simply be better off for the purpose of callba= cks taking the callback function as a normal argument; this way you can not spe= cify a default of nil if you don't want that, or you could give your own default. def a(p) $cb =3D p end a(lambda do |arg| p arg.inspect end)=20 hope this helps -kyle --=20 http://mas.cs.umass.edu/~rawlins -- There is no friend anywhere. --FFoLq8A0u+X9iRU8 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) iD8DBQE9B46bncsSsHSBypARAkqKAKCl899z4lmfxgwSBqxEx3kels0EugCfU3/J l4zB5CIe2pkPR+Y7dRjNuGI= =jLrV -----END PGP SIGNATURE----- --FFoLq8A0u+X9iRU8--