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!
I will start with && and || operators.
“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
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
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?