Understanding Ruby Comparison and Control Flow Operators

This afternoon, I had a chance to discuss about something with my pair about the difference between comparison operators and control flow operators in Ruby. Yes! What is the actual difference between && || operators and “and” “or” operators?

I started Ruby around 4 years ago and I wrote a code like this

if (a == true and b == true)
  # my code
end

And I swear I won’t do that again!

Why?

I will start with && and || operators.

Those are the operators that you met frequently, even in the early age of your programming career. Whether it’s PHP, Ruby, Javascript, C, or C++, you always use the operators for comparison which mostly written for conditional, because they return boolean object type. If I describe it in words:

If the box has 3 balls and the colour of the box is blue then I will say ‘Great!’

It can be translated to

if (box.size == 3 && box.colour == 'blue')
  puts 'Great!'
end

It’s super simple!

Now, what about “and” and “or” operators?

I’m going to give you an example of logic description which will be translated to code using control flow operators.

Please find a user data, if it’s found then show me the name

Above description can be translated to

user = User.find_by_id(1) and user.full_name

If User.find_by_id successfully fetch data then it will execute the next code. But, if it doesn’t find anything, then it will never execute user.full_name.

One other example that I can show is

Please find a user, if it’s not found then show me an error message. But, if it’s found then show me the username

Below is the translation into code

user = User.find_by_id(1) or puts "No user found!" and user.username

It will try to fetch a user data, but this time if it fails to fetch a data then it will show “No user found!”. With “or” keyword, it will execute the next code if the previous code fails (returning nil or false).

Well, that was a simple thing, yet fundamental that I learned today. Anyway, I think these control flow keywords are available too in PHP, right? Are they available in other languages too?

Advertisements

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 )

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