Monday 4 June 2007

Ruby & rails - thanks for nice weekend ;)

It is early Monday morning and I need to write it (however no one wants to read it).

My wife spent past 2 days in mountains (Tatry, never mind). I spent it with Rails. Or rather - with ruby. When I dig into Rails I sow all these :foo, :bar so I couldn't move forward without knowing WHAT DOES IT MEAN???

This is a time when books like "Programming Ruby" comes in hand. What I think now?

Ruby is really easy especially if you know perl :) I am not a fun of TIMTOWTDI and Ruby seems to be also... However there are ugly constructions like "reverse if/unless" so Ruby programmers can step to the Black World of Many-F^&*-Ways-To-Do-It... but they probably don't want, do they?

We need some ways in language to make different things looking different and Ruby allow us to do it. Oh, it looks like expressive programmers manifesto ;)

So once again:
Pretty nice language, with this object logic you thought "how it will be simple to have it done ONE WAY, objective". Really worth trying. Simple. Code looks nice.

I thought Ruby is too perlish and probably I should focus on clean Python syntax. However Ruby is better designed than Python. There are no "dirties" like:


$> Python
>>> foo = "bla bla bla"
>>> foo.upper()
'BLA BLA BLA'
>>> foo.len()
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: 'str' object has no attribute 'len'
>>> len(foo)
11


In Ruby it is simple:
(even Python's dir(object) in Ruby is objective: obj.methods or even better obj.methods.sort)

irb> foo.upcase
=> "BLA BLA BLA"
irb> foo.length
=> 11


You can write it "Pythonic/java" way with parentheses, but they are optional:
irb> foo.length()
=> 11

Ok, so what about :foo, :bar and @others?


var = 123 # string
$var = 123 # global variable
@var = 123 # class variable
@@var = 123 # package variable


Classes:


def class1
attr_reader :duration
end

# which is a shortcut of:

def class1
attr_reader(:duration)
end

# which is a shortcut of:

def class1
def duration
@duration
end
end

# which is a shortcut of:

def class1
def duration
return(@duration)
end
end


:duration - means you passing "object symbol" not "value of it" (aiui)

If you come from Java world, now you know we don't need "make setters/getters" refactoring option in our Ruby editor/IDE ;)

We can strip methods parentheses(), we can strip returns, we can focus on code logic - this is why frameworks written in Ruby can be pretty nice, easy to understand and to remember. I just wonder when I will see a book named "Ruby best practices".

No comments: