Ruby Programming/Syntax/Method Calls

A method in Ruby is a set of expressions that returns a value. With methods, one can organize their code into subroutines that can be easily invoked from other areas of their program. Other languages sometimes refer to this as a function. A method may be defined as a part of a class or separately.

Method Calls
Methods are called using the following syntax:

With or without parameters, Ruby allows method calls without parentheses:

Parentheses are needed to chain method calls; for example:

Method Definitions
Methods are defined using the keyword  followed by the method name. Method parameters are specified between parentheses following the method name. The method body is enclosed by this definition on the top and the word  on the bottom. By convention method names that consist of multiple words have each word separated by an underscore.

Example:

Return Values
Methods return the value of the last statement executed. The following code returns the value.

An explicit return statement can also be used to return from function with a value, prior to the end of the function declaration. This is useful when you want to terminate a loop or return from a function as the result of a conditional expression.

Note, if you use "return" within a block, you actually will jump out from the function, probably not what you want. To terminate block, use break. You can pass a value to break which will be returned as the result of the block:

In this case, six will have the value 6.

Default Values
A default parameter value can be specified during method definition to replace the value of a parameter if it is not passed into the method.

The method call above will output:

The following is a syntax error in Ruby 1.8

The above code will work in 1.9.2 and will be logically equivalent to the snippet below

Variable Length Argument List, Asterisk Operator
The last parameter of a method may be preceded by an asterisk(*), which is sometimes called the 'splat' operator. This indicates that more parameters may be passed to the function. Those parameters are collected up and an array is created.

In the example above the output would be ['a', 'b', 'c'].

The asterisk operator may also precede an Array argument in a method call. In this case the Array will be expanded and the values passed in as if they were separated by commas.

has the same result as:

Another technique that Ruby allows is to give a Hash when invoking a function, and that gives you best of all worlds: named parameters, and variable argument length.

You see, the arguments for accepts_hash got rolled up into one hash variable. This technique is heavily used in the Ruby On Rails API.

Also note the missing parenthesis around the arguments for the accepts_hash function call, and notice that there is no { } Hash declaration syntax around the :arg1 => '...' code, either. The above code is equivalent to the more verbose:

Now, if you are going to pass a code block to function, you need parentheses.

In versions of Ruby since Ruby 2.0, it is also possible to use the new built-in keyword arguments that make above technique somewhat easier. The new syntax is as follows: Above function can now be called as test_method(1,2), test_method(1,2, c: somevalue), test_method(1,2, d:someothervalue), test_method(1,2, c:somevalue, d:someothervalue) or even test_method(1,2, d: someothervalue, c: somevalue). In this example, parentheses are again not required unless you want to chain the result to another function or method right away. Note that this does mean that you 'have' to pass on names for (in this case) the 'c' and 'd' values you pass into the function, whenever you want to include them Calling the method like test_method(1,2,3,4) will not work.

Keyword Arguments are especially helpful whenever there is a lot of non-required options that might be passed into a function. Specifying the names whenever they are used makes the resulting function calls very readable.

The Ampersand Operator
Much like the asterisk, the ampersand(&) may precede the last parameter of a function declaration. This indicates that the function expects a code block to be passed in. A Proc object will be created and assigned to the parameter containing the block passed in.

Also similar to the ampersand operator, a Proc object preceded by an ampersand during a method call will be replaced by the block that it contains. may then be used.

Introduction
Ruby provides the programmer with a set of very powerful features borrowed from the domain of functional programming, namely closures, higher-order functions, and first-class functions [1]. These features are implemented in Ruby by means of code blocks, Proc objects, and methods (that are also objects)—concepts that are closely related and yet differ in subtle ways. In fact, I found myself quite confused about this topic, having difficulty understanding the difference between blocks, procs, and methods as well as unsure about the best practices of using them. Additionally, having some background in Lisp and years of Perl experience, I was unsure of how the Ruby concepts map to similar idioms from other programming languages like Lisp’s functions and Perl’s subroutines. Sifting through hundreds of newsgroup posts, I saw that I am not the only one with this problem and, in fact, quite a lot of “Ruby Nubies” struggle with the same ideas.

In this article I lay out my understanding of this facet of Ruby, which comes as a result of extensive research of Ruby books, documentation, and comp.lang.ruby, in sincere hope that other people will find it useful as well.

Procs
Shamelessly ripping from the Ruby documentation, Procs are defined as follows: Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.

A useful example is also provided:

Procs play the role of functions in Ruby. It is more accurate to call them function objects, since like everything in Ruby they are objects. Such objects have a name in the folklore - functors. A functor is defined as an object to be invoked or called as if it were an ordinary function, usually with the same syntax, which is exactly what a Proc is.

On Wikipedia, a closure is defined as a function that refers to free variables in its lexical context. From the example and the previous definitions, it is obvious that Ruby Procs can also act as closures. Note how closely it maps to the Ruby definition blocks of code that have been bound to a set of local variables.

More on Procs
Procs in Ruby are first-class objects, since they can be created during runtime, stored in data structures, passed as arguments to other functions and returned as the value of other functions. Actually, the gen_times example demonstrates all of these criteria, except for “passed as arguments to other functions”. This one can be presented as follows:

There is also a shorthand notation for creating Procs - the Kernel method lambda [2] (we’ll come to methods shortly, but for now assume that a Kernel method is something akin to a global function, which can be called from anywhere in the code). Using lambda the Proc object creation from the previous example can be rewritten as:

Actually, there are two slight differences between lambda and Proc.new. First, argument checking. The Ruby documentation for lambda states: Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called. Here is an example to demonstrate this:

Second, there is a difference in the way returns are handled from the Proc. A return from Proc.new returns from the enclosing method (acting just like a return from a block, more on this later):

While return from lambda acts more conventionally, returning to its caller:

With this in light, I would recommend using lambda instead of Proc.new, unless the behavior of the latter is strictly required. In addition to being a whopping two characters shorter, its behavior is less surprising.

Methods
Simply put, a method is also a block of code. However, unlike Procs, methods are not bound to the local variables around them. Rather, they are bound to some object and have access to its instance variables [3]:

A useful idiom when thinking about methods is that you are sending messages to the object that the method is defined for. Given a receiver - an object that has some method defined - we send it a message, which contains the name of the method, and optionally provides the arguments that the method would receive. In the example above, calling the method arbo without any arguments, is akin to sending a message with just “arbo” as the argument.

Ruby supports the message sending idiom more directly, by including the send method in class Object (which is the parent of all objects in Ruby). So the following three lines are equivalent to the arbo method call:

Note that methods can also be defined in the so-called “top-level” scope, which is not inside any user-defined class. For example:

While it seems that the method say is “free-standing”, it is not - Ruby silently tucks it into the Object class, which represents the scope of your application:

But this doesn’t really matter, and for all practical purposes say can be seen as an independent method. Which is, by the way, just what’s called a “function” in some languages (like C and Perl). The following Proc is, in many ways similar:

The [] construct is a synonym to call in the context of Proc [4]. Methods, however, are more versatile than procs and support a very important feature of Ruby, which I will present right after explaining what blocks are.

Blocks
Blocks are so closely related to Procs that it gives many newbies a headache trying to decipher how they actually differ. I will try to ease on comprehension with a (hopefully not too corny) metaphor. Blocks, as I see them, are unborn Procs. Blocks are the larval, Procs are the insects. A block does not live on its own - it prepares the code for when it will actually become alive, and only when it is bound and converted to a Proc, it starts living:

Is that it, is that what all the fuss is about, then ? No, not at all. The designer of Ruby, Matz saw that while passing Procs to methods (and other Procs) is nice and allows high-level functions and all kinds of fancy functional stuff, there is one common case that stands high above all other cases - passing a single block of code to a method that makes something useful out of it, for example iteration. And as a very talented designer, Matz decided that it is worthwhile to emphasize this special case, and make it both simpler and more efficient.

Passing a block to a method
No doubt that any programmer who has spent at least a couple of hours with Ruby has been shown the following examples of Ruby glory (or something very similar):

(Note that  is equivalent to  .)

Such code is, in my opinion, the part of what makes Ruby the clean, readable, and wonderful language it is. What happens here behind the scenes is quite simple, or at least may be depicted in a very simple way. Perhaps Ruby may not implement it exactly the way I am going to describe it, since there are optimization considerations surely playing their role, but it is definitely close enough to the truth to serve as a metaphor for understanding.

Whenever a block is appended to a method call, Ruby automatically converts it to a Proc object but one without an explicit name. The method, however, has a way to access this Proc, by means of the yield statement. See the following example for clarification:

The method do_twice is defined and called with an attached block. Although the method did not explicitly ask for the block in its arguments list, the yield can call the block. This can be implemented in a more explicit way using a Proc argument:

This is equivalent to the previous example but using blocks with yield is cleaner and better optimized since only one block is passed to the method. Using the Proc approach, any amount of code blocks can be passed:

This is important to note that many people frown at passing blocks and prefer explicit Procs instead. Their rationale is that a block argument is implicit and one has to look through the whole code of the method to see if there are any calls to yield there, while a Proc is explicit and can be immediately spotted in the argument list. While this is simply a matter of taste, understanding both approaches is vital.

The ampersand (&)
The ampersand operator can be used to explicitly convert between blocks and Procs in a couple of cases. It is worthy to understand how these work.

Remember how I said that although an attached block is converted to a Proc under the hood, it is not accessible as a Proc from inside the method ? Well, if an ampersand is prepended to the last argument in the argument list of a method, the block attached to this method is converted to a Proc object and gets assigned to that last argument:

Another (IMHO far more efficacious) use of the ampersand is the other-way conversion - converting a Proc into a block. This is very useful because many of Ruby’s great built-ins, and especially the iterators, expect to receive a block as an argument, and sometimes it’s much more convenient to pass them a Proc. The following example is taken right from the excellent “Programming Ruby” book by the pragmatic programmers:

The collect method expects a block, but in this case it is very convenient to provide it with a Proc, since the Proc is constructed using knowledge gained from the user. The ampersand preceding calc makes sure that the Proc object calc is turned into a code block and is passed to collect as an attached block.

The ampersand also allows the implementation of a very common idiom among Ruby programmers: passing method names into iterators. Assume that I want to convert all words in an Array to upper case. I could do it like this:

This is nice, and it works, but I feel it’s a little bit too verbose. The upcase method itself should be given to map, without the need for a separate block and the apparently superfluous x argument. Fortunately, as we saw before, Ruby supports the idiom of sending messages to objects, and methods can be referred to by their names, which are implemented as Ruby Symbols. For example:

This, quite literally, says send the message/method upcase to the object “Erik”. This feature can be utilized to implement the map {|x| x.upcase} in an elegant manner, and we’re going to use the ampersand for this! As I said, when the ampersand is prepended to some Proc in a method call, it converts the Proc to a block. But what if we prepend it not to a Proc, but to another object? Then, Ruby’s implicit type conversion rules kick in, and the to_proc method is called on the object to try and make a Proc out of it. We can use this to implement to_proc for Symbol and achieve what we want:

Dynamic methods
You can define a method on "just one object" in Ruby.

Or you can use define_(singleton_)method, which preserves the scope around the definition, as well.

Special methods
Ruby has a number of special methods that are called by the interpreter. For example:

This does something silly but  is an important part of meta-programming in Ruby. In Ruby on Rails it is used extensively to create methods dynamically.

Another special method is  that ruby calls whenever a class instance is created, but that belongs in the next chapter:  Classes.

Conclusion
Ruby doesn’t really have functions. Rather, it has two slightly different concepts - methods and Procs (which are, as we have seen, simply what other languages call function objects, or functors). Both are blocks of code - methods are bound to Objects, and Procs are bound to the local variables in scope. Their uses are quite different.

Methods are the cornerstone of object-oriented programming, and since Ruby is a pure-OO language (everything is an object), methods are inherent to the nature of Ruby. Methods are the actions Ruby objects do - the messages they receive, if you prefer the message sending idiom.

Procs make powerful functional programming paradigms possible, turning code into a first-class object of Ruby allowing to implement high-order functions. They are very close kin to Lisp’s lambda forms (there’s little doubt about the origin of Ruby’s Proc constructor lambda)

The construct of a block may at first be confusing, but it turns out to be quite simple. A block is, as my metaphor goes, an unborn Proc - it is a Proc in an intermediate state, not bound to anything yet. I think that the simplest way to think about blocks in Ruby, without losing any comprehension, would be to think that blocks are really a form of Procs, and not a separate concept. The only time when we have to think of blocks as slightly different from Procs is the special case when they are passed as the last argument to a method which may then access them using yield.

That’s about it, I guess. I know for sure that the research I conducted for this article cleared many misunderstandings I had about the concepts presented here. I hope others will learn from it as well. If you see anything you don’t agree with - from glaring errors to small inaccuracies, feel free to amend the book.