On Jan 6, 2011, at 2:11 PM, Rail Shafigulin wrote:

>> you are right. [] is a special function among a list of other (like
>> []= / + - @-) that don't work regularily, so as to allow syntactic
>> sugar. This makes a great fit when you want to build Hash-like or
>> Array-like objects, just make sure not to over-use it.
> 
> where can i read more about this syntactic sugar? is there some sort of 
> tutorial?

I'm not sure if you are asking about 'syntactic sugar' in general or
specific examples of such in Ruby.

In a general sense, syntactic sugar is a textual shortcut that a
language parser/interpreter supports to provide alternate (and hopefully
more useful) syntax for a standard feature.

The general Ruby syntax for method calls:

	receiver.method(arg1, ar2)

is somewhat ugly when the method name is '[]':

	receiver.[](3)

But the syntactic sugar provided by Ruby's parser lets it accept

	receiver[3]

while interpreting it as just a standard method call to the
method named '[]' with an argument of 3, just as if you
had used the standard method calling syntax:

	receiver.[](3)

Another example of this is Ruby's attribute writer methods
('setter methods'):

	customer.name = "Joe Smith"

is syntactic sugar for:

	customer.name=("Joe Smith")

which is just the standard method call syntax when the method
name is 'name='.

Operators are another example of this in Ruby.

	a = 1 + 2

is syntactic sugar for

	a = 1.+(2)

where 1 is the receiver, '+' is the method name, and 2 is the
first and only argument to the method.  A slightly more
complicated example

	a += 1

is sugar for

	a = a + 1

which is sugar for

	a = a.+(1)

I don't know of a definitive list of these 'sugars' but I'm sure there are all mentioned somewhere in "The Ruby Programming Language", which is my favorite Ruby book if you are interested in a reference style exposition rather than a tutorial style exposition.

Gary Wright