From: Brian Candler Date: 2003-04-10T05:17:09+09:00 Subject: Re: Proc Question On Thu, Apr 10, 2003 at 01:57:18AM +0900, Chris Pine wrote: > A proc is an object. A method isn't. Consider a method of zero arguments: > > def fiveSquared > 5 * 5 > end > > You can call this method simply by writing `fiveSquared', and Ruby *knows* > you want the method called, because that's the only thing you can do with > methods. Well, there's a bit more to it than that really. If I follow your above code with: puts fiveSquared fiveSquared = 9 # OK so not very strong mathematically! puts fiveSquared Then I get "25" then "9" printed. 'fiveSquared' by itself is just a symbolic reference; in the second location it's treated as a local variable access because of the previous assignment to fiveSquared. But after that: puts fiveSquared() puts self.fiveSquared both give 25. With a parenthesised argument list, or an explicit receiver, it has to be interpreted as a method call; there is now no ambiguity. Furthermore, a method (once defined) is in fact an object, or at least you can get hold of an object which encapulates it: m = method(:fiveSquared) #>> # m.call #>> prints 25 > A proc, however, can be assigned to a variable, passed into methods, etc. Methods (like the one assigned to 'm' above) can be passed around too. > In fact, unlike methods, procs are unnamed. (Am I right about methods > intrinsically having names?) I think so. The lowest-level way I know how to define a method is with define_method(:sym,proc) so you have to assign it a symbolic name at that point. It remembers it too (e.g. m.inspect tells you its name) > fiveSquared = proc {5 * 5} > > `fiveSquared' is just a variable. Indeed, which happens to contain a reference to a Proc object. But even now, fiveSquared() will still call the method, not this Proc object. > have such different syntaxes (syntices?). Same for method parameter list > `(...)' and block parameter list `|...|'. The block parameter list is closer to parallel assignment than a method call. e.g. the following are pretty much the same: a, b, *c = 1, 2, 3, 4 .. do stuff .. x = proc { |a,b,*c| .. do stuff .. } x.call(1,2,3,4) > Still, it's important to realize > that methods and functions (which is what procs are) are *different* Ruby doesn't have "functions" - it does have Methods and Procs. Someone coming from a background of, say, C, would probably consider a Method to be the closer analogy to a C function: int adder(int a,b) { return a+b; } def adder(a,b) a+b end as opposed to the Proc, which is perhaps a little bit like a "pointer to a function", but not very much :-) Cheers, Brian.