I’ve been reviewing my coding skills in Ruby to keep myself sharp and thought I’d write a post about some gotchas that I came across during my studies.
== === .eql? .equal?
Even newbies to Ruby know what ==
does. It’s an operator that compares the value of two operands.
But what if we want to be more discriminating about our comparison? The ==
only compares values and doesn’t check the Class of the objects. How do we also for the same Class? If you come from a Javascript background, you might be inclined to say ===
. BUT WAIT
It turns out ===
in Ruby and Javascript behave differently. If you’d like to compare value AND class in ruby, you have to invoke the method .eql?
, while ===
is used to compare the class of the object, usually in when
clauses of case
statements.
Finally when we want to compare if an object is the very same object, as in they not just have the same value and class, but also the same object_id
, we use the .equal?
method.
Order of Operations and Precedence
This question came up on a sample interview question. Consider the following
Although both statements return false
, the value of y
is actually true
. In ruby &&
has a higher precedence than =
in the order of operations and and
has a lower precedence than =
. So what ends up happening is more like following
So keep in mind you should use &&
and ||
for comparisons and and
and or
for flow control.