Why Ruby

When I talk Ruby (the programming language – duh) to some people, I’m often asked — what’s so good and different about Ruby? It’s normally quite hard for me to be articulate and yet not sound like a fan-boy, so I’m often annoyed when I can’t explain it too well.

That’s what blogs are for.

I’ll just write down a couple of things at the top of my head that I think is really cool about Ruby. This is totally unstructured and there’s plenty more of really cool stuff, but these are some that stuck to my mind.

First is that everything is an object. So something like this can be done:

3.times do
p "something"

which loops and prints “something” 3 times. How cool is that?
Another one, slightly more elaborate:

solution_architects = ['Oscar', 'Ravi', 'Jimmy', 'Gnani', 'Andrew']
lab_managers = ['Bernard', 'Pierre', 'Thomas']
person = "Oscar"
case person
when *solution_architects
p "Come up with a good solution!"
when *lab_managers
p "Manage the team well!"

This prints ount “Come up with a good solution!” No more mucking around with looping around to check if the array contains an object.

Last one, from the Pickaxe book, which needs a bit more explanation:

def fibonacci_up_to(max)
i1, i2 = 1, 1        # 1
while i1 < = max
yield i1 # 3
i1, i2 = i2, i1+i2 # 2

fibonacci_up_to(1000) { |f| print f, " " }  # 4

What did I just do?

  1. #1 – parallel assignment, very brief, very understandable
  2. #2 – again parallel assignment, notice that I can do a variable swap without messy temporary variables – yuck
  3. # 3 – yield is a special keyword that allows me to pass entire function blocks to a method!
  4. # 4 – passing the function block, within the curly braces ‘{}’

Think again — you can pass function blocks to a method! Not just miserly variables but true-blue blocks of code!

How cool is that? Now I’m really repeating myself.

3 thoughts on “Why Ruby

  1. Some bad formatting in the post, which I had to modify again and again until I got it correct. Not sure if it’s WordPress or me :)

    Nice article!

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s