Ruby Syntactic Sugar


Programmers use the term syntactic sugar to refer to special rules that let you write your code in a way that doesn't correspond to the normal rules but that is easier to remember how to do and looks better.

Let us say we want to set the name of a dog. As a starting point, name can be set along with everything else at object creation time, as in the example below.

Let's write a set_name method that allows us to set, or reset, the name of an existing dog. We'll also rewrite the initialize method so that it doesn't expect a name:

Ruby allows you to define methods that end with an equal sign (=). Let's replace set_name with a method called name=

name= does exactly what set_name did, and in spite of the slightly odd method name, you can call it just like any other method:

Here's the modified example - p050newdog.rb

The equal sign gives you that familiar "assigning a value to something" feeling, so you know you're dealing with a setter method. It still looks odd, but Ruby takes care of that, too.

Ruby gives you some syntactic sugar for calling setter methods. Instead of this:

you're allowed to do this:

When the interpreter sees the message "name" followed by " =", it automatically ignores the space before equal sign and reads the single message "name=" - a call to the method whose name is name=, which we've defined. As for the right-hand side: parentheses are optional on single arguments to methods, so you can just put 'Benzy' there and it will be picked up as the argument to the name= method.

IN RAILS: Method calls using the equal-sign syntax are common in Rails applications.

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on rubylearning.com and in the course at rubylearning.org is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.