Day 2 starts with one of the most valuable programming exercises. What can I do with an object? Just ask it:
self.methods
With ‘self’ being the current object, the above question returns a list of all the questions ‘self’ knows how to answer.
Every object in Ruby can be asked this question. So many languages are only object-oriented, not object-saturated like Ruby. Back in my REALbasic days, I’d scan an objects auto-complete menu looking for the right method or attribute. More than once I was baffled in the differences between objects. I was also baffled by the difference between ‘self.’ and ‘me.’ in RB. No sign of ‘me.’ yet in Ruby.
If you ask 10 people “What is your name?”, you’ll receive 10 different answers. In programming, this is called ‘polymorphism’ and it means different objects can respond differently to the same question. A useful example comes from Object-Oriented Thought Process: all shapes – circles, squares, triangles – have a perimeter and an area. Thought the equation to calculate each is different.
Occasionally, I’ll hit a programming problem where it makes sense to return multiple values out of a method. Normally, I take this as a cue I’m not being clear about what I’m trying to accomplish and make 2 methods. Looks like Ruby can return multiple values separated by commas. Seems useful for debugging.
The Ruby syntax is truly Zen-like. No semi-colons explicitly declaring the end of a line made me smile. Now Slagell’s saying ‘return’ at the end of a method isn’t needed either. Without an explicit ‘return’, the last thing evaluated is returned.
me.jump(up, down)
Here’s a useful tip I learned going through today’s exercises. Between 2 datetime strings, Ruby doesn’t know what ‘+’ means. For example:
return Time.now + Time.now
returns an error, where as
return "it's #{Time.now}" + ", now it's #{Time.now}."
spits out a sentence.
Good to know.
Al Abut’s 2nd day
This post documents my journey through Sam’s Teach Yourself Ruby in 21 days. I’ll be joining Al Abut in his effort to learn Ruby and blog along the way.