Wednesday, June 18, 2008

I love me some Ruby

So, I'm learning Ruby and Rails at home, and I'm absolutely loving it.

I love the little idiomatic stuff that make typing in it so concise.

Let's say that I have a list called mylist. I want to add an object to the list, foo.

In Java, I'd have to go something like this.



In Ruby, it's just this:



It's not earth shattering, but there are a dozen examples like this that I really like. If you understand the symbols and operators of the language, it actually reads just fine. Maybe I'm getting cranky in my old age and not wanting to type out all that stuff as much anymore.

Another perhaps bigger example was the "attr_accessor" convenience method.



What just happened here? For me, the critical part was the getter/setter bits. In Java, I'd have to select a menu option in Eclipse to generate the getter's and setter's for this class. Imagine a class with 10 fields in Java. You are NOT gonna type out those methods.

In the Ruby case, it's just 1 line of code. And, you can add more fields to the same line. "attr_accessor" tells us that what are our accessor methods. Nice!

See also attr_reader and attr_writer which do as you would expect, allowing only read or only write methods.

No comments: