The purpose of this post is just to be used as a reference to those new to Ruby programming who want an example for each operator. If you’re coming from another programming language, you’ll know most of these but if you’re new to Ruby, save this page as a reference until you become best friends.
I’m sure you know how to use arithmetic operators
% modulus and
** exponential power operators already.
a && b
The AND operator you’ll be familiar with from other programming languages. If both sides of the operator are true then the method returns true.
true && true#=> truetrue && false#=> falsetrue && nil#=> nil# && can be replaced by 'and' but don't do this.
a || b
Similar to the AND operator, OR compares both operands to compare truthiness.
true || true#=> truetrue || false#=> truefalse && false#=> false# || can be replaced by 'or' but don't do this.
!(a && b)
You’ll want to use the bang operator when you want to compare the reverse state of the provided condition.
!(true && true)#=> false!(true && false)#=> true!(false && false)#=> true# ! can be replaced by 'not' but don't do this.
I don’t often use this operator as it confuses a lot of beginners working on your project. Check out this example to get a simple understanding:
a = truea ? true : false#=> trueNow let’s mix a bit of previous knowledge with this operator:a = trueb = falsea && b ? 'Yay! True.' : 'Sorry. False.'#=> "Sorry, False."a || b ? 'Yay! True.' : 'Sorry. False.'#=> "Yay!, True."
In almost every Ruby class you’ll find this operator. It checks if either side are equal or not.
true == true#=> truetrue == false#=> false100 == 100#=> true
== is the operator
!=. Which you might expect from the above examples does the reverse. If both operands are not the same then the condition is true.
10 != 20#=> truedef age(dob)Age.new(dob)endputs age('23-07-2015') != 18 ? 'Have a coke.' : 'Have a beer.'#=> "Have a coke."
Similar to ==, === checks for equality. If both operands are not of the exact same then it will be false. The examples below should clear this up.
10 === 10#=> true10 === '10'#=> false
As you’ll notice above, I compared the age of someone with a given target value. Let’s get started with a few examples below.
10 > 5#=> true10 > 20#=> false10 >= 10#=> true10 >= 5#=> true5 < 10#=> true10 <= 10#=> true10 <= 5#=> false
This is my favourite. It compares each operand and returns either -1, 0 or 1. I’ve used this so many times when building scoring algorithms.
The best way to describe this is with an example:
5 <=> 10#=> -110 <=> 10#=> 015 <=> 10#=> 1
There are a lot more Ruby operators but I’ll post again soon covering