Ruby: day 1

So. Ruby. I was pleased to read that ruby is an object-oriented language and takes object-orienting even a step further than Java.
I haven’t worked with a language that is coded from the command prompt before so I am interested in how that is going to work out.

After having done a few of the basic excercises from the book I quickly found myself amazed at the ease of Ruby programming.
The language feels like writing down your thoughts instead of following preset rules. I especially like the untill funcionality.

>> x = x - 1 until x == 1
=> nil
>> x
=> 1

It just feels (and reads) way easier than writing complicated while or for loops.
Then I came accross the following statement: “So, everything but nil and false evaluate to true. C and C++ programmers, take note. 0 is true!”.
While I’m not a C or C++ programmer, this still struck me as odd. In every past programming experience I have had, 0 would alwayse evaluate to false. So I’m guessing I will make this mistake a lot in the future.
(Note to self: when encountering a bug, check if 0 is expected to be false instead of true!!!)

Something about and or || | && & ???

And then the topic of type checking. Ruby does not do type checking untill you actually try to execute the code (dynamic typing). You can’t catch your errors when writing functions, but Ruby has its advantages on this aspect as well: Duck typing. Duck Typing means an object type is defined by what it can do, not by what it is.

>> i = 0
=> 0
>> a = ['100', 100.0]
=> ['100', 100.0]
>> while i> puts a[i].to_i
>> i = i + 1
>> end

In the code above duck typing is demonstrated. Array a consists of a String and a float element. Both can be converted into integers by the to_i method. If it walks like a duck and quacks like a duck, it’s a duck.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s