2009-02-21

ASCII Art

Ruby 1.9 introduces some nice ways to write less code and make it look more mysterious at the same time. It's enough to have a look at the following pieces of ASCII art, each line is a valid expression in Ruby 1.9:

->(){}[]
0-->(){0}[]<--0
{x: :x}
{:+@=>->{:-@}}

What they mean? First, there's a new syntax for defining lambdas:
->(args){body}
, and when defining a lambda with no args and no body, and then calling it by
[]
, you obtain the first line. There's also another way to call a lambda or a proc now:
some_lambda.(args)
. This allows us to write
->()[].()
, of someone finds this even more confusing than the first option.

The second line should not be a problem now, it says
(0 - ->{0}.call) < -(-0)
. Yes, in Ruby even
--------1
is a valid expression. It's as they say in the primary school: minus and minus gives plus.

There's also a new syntax for defining hashes that have symbols as keys:
{k:val}
is equivalent to
{:k=>val}
. In our example however one has to put a whitespace between the two colons or else the interpreter is confused, because two colons is another token - for calling a function or getting a constant.

And the last line is just some creative nothing. It uses the symbols
:+@
and
:-@
which are normally used as method names for unary plus and minus. See yourself:
5.-@()
gives
-5
.

There's a lot of articles (and blog entries on various Ruby blogs) that cover the differences between Ruby 1.8 and Ruby 1.9 so if you're interested, just look for them and you'll find easily. One that is worth reading if you'd like to know more than is usually contained in short presentations:

Ruby 1.8 vs Ruby 1.9

And a nice wrap up: Useful Ruby 1.9 links

No comments: