Precedence of to-block unary `&` - ruby

Consider the following Ruby code:
[1,3].any? &:even? || true
# => false
[1,3].any? &nil || :even?
# => false
[1,3].any? &nil || :odd?
# => true
So it seems that Boolean-or || has higher precedence than to-proc unary &. I didn't expect this. Is that right, and is it documented anywhere?

This is what the (wrongly-maligned) and and or keywords are for. You're supposed to write that as
[1,3].any? &:even? or true
As for why this happens--I can't find documentation for this--but I think it actually has more to do with optional parentheses and the restrictions of unary &.
Unary & is special. "Normal" operators like ~ are essentially syntactic sugar over method calls; you can put them wherever you want. But & is only allowed in method arguments, and even then only at the end.
foo x, &bar
# NameError, determined at runtime because it has to see if any of these names are defined
foo &bar, x
# SyntaxError! Didn't even make it past the parser
y = bar
# NameError
y = &bar
# SyntaxError!
And when you leave parentheses out from a method call, it slurps up pretty much everything, stopping only at super-low-precedence stuff like if/unless/and/or.
foo bar baz if true
# same as
foo(bar(baz)) if true
So your example is equivalent to
[1,3].any?(&:even? || true)
Now if & were somehow high-precendence this is either a totally normal value to be evaluated at runtime true or it's a highly-restricted special syntactic construct &:even?. It's not great to discover syntax errors at runtime, so I guess the devs chose to solve it the easy way: make & super low precedence. That way the parser can just verify the syntax rules and ignore the block argument itself (which has to be evaluated at runtime).

When the & is not preceded by an object (unary) and is immediately followed by by anything else (&nil in this case). It will be parsed as an attempted to_proc method call otherwise it will be treated as a method call on the receiver e.g.
nil&nil
#=> false
Is equivalent to nil.&(nil)
So in your case ([1,3].any? &nil || :even?) it is being parsed as [1,3].any?(&(nil || :even?)) because & (to_proc method call) has a lower precedence than logical || and needs to know the result of nil || :even? to proceed.
However, operational and (&) requires a receiver (not unary) but does hold a higher precedence than the logical or (||) e.g. [1,3].any? &nil&nil || :even? which would evaluate to
[1,3].any?(&(nil.&(nil) || :even?)
#=> false
# Or
[1,3].any?(&(nil & nil || :even?)
#=> false
Where strangely enough it is clear that operational and (&) has a higher precedence than logical or (||)
Further examples
true & nil || :even?
#=> :even?
true & :even?
#=> true
[1,3].any? &true&true || :even?
#=> TypeError: wrong argument type TrueClass (expected Proc)
# Okay no problem
class TrueClass
def to_proc
->(*_) { true }
end
end
[1,3].any? &true&true || :even?
#=> true
[1,3].any? &true || :even?
#=> true
Even stranger is that the unary & allows for nil but essentially ignores it from block_given? but any other object that does not implement to_proc raises a TypeError
def no_block
block_given? ? yield('Yes') : 'No'
end
no_block &nil
#=> "No"
no_block &false
#=> TypeError: wrong argument type FalseClass (expected Proc)

Related

What does #foo || #foo = "bar" mean in Ruby and why?

What does #foo || #foo = "bar" mean in Ruby? To me, it seems to have the meaning of #foo || (#foo = "bar") instead of (#foo || #foo) = "bar". This, however, contradicts with the fact that || has a higher precedence than = in Ruby.
I am aware that || in Ruby is a short-circuit operator. I also understand that || is to be evaluated before = according to precedence. What I don't understand is that #foo = "bar" seems to be the right operant of ||. According to the precedence table, the right operant of || should be #foo, and the expression should be equivalent to (#foo || #foo) = "bar", which is illegal.
Ruby uses Short-circuit evaluation, and so it evaluates the first argument to decide if it should continue with the second one.
In case of #foo || #foo = "bar", OR operation is performed in such a way that when first argument is found nil, second argument is evaluated which is assignment statement. IF first argument is found/truthy then it will ignore second argument(statement in this case)
Note, it does not just assign value to #foo, complete logical statement return value after assignment.
If you write, #foo = #foo || 'sd' logical operation are performed first & then assigned.
I think in the end it truly is simply Short-circuit-evaluation as ray mentions in his answer, but I think the documentation is lacking in this regard.
|| is a short-circuit operator so as evaluation proceeds left to right, as soon as it finds a true, it is done and will return true, otherwise it will proceed to the right
the modifier-if (also listed on the page you linked to) has lower precedence than the assignment =, however assignment is not a short-circuit operator, so code like
foo = "not set"
is_true = false
foo = 42 if is_true
puts foo
will print
not set
while code such as:
foo = "not set"
is_true = true
foo = 42 if is_true
puts foo
will print
42
|| is a short-circuit operator so code such as this:
foo = 0
foo || foo = 42
puts foo
will print
0
because the left hand foo is not nil, so there is no reason to evaluate the right hand side.
while code such as this:
foo = nil
foo || foo = 42
puts foo
will print
42
since foo is nil, evaluation will continue to the right side of the || until it his a something that is true or return the last expression which will be true or false.
I agree however that the document you point to would imply that
x || y = z should be based on precedence could be interpreted as (x || y) = z which would not be legal. However it's also obvious that this would be the same as trying to assign a value to a boolean.
For example:
(true || true) = 42
is a syntax error
as does:
a = nil
b = nil
(a || b) = 42
yet
a = nil
b = nil
a || b = 42
puts b
results in
42
Simply, your interpretation of the precedence rule is wrong.
Precedence rule applies when there is ambiguity. With assignment syntax, the left hand side of = has to be a single token that is legal as a constant or some type of variable.
#foo || #foo = ...
can be only interpreted as
#foo || (#foo = ...)
and there is no ambiguity here, hence no issue of precedence.
What the precedence rule is concerned with is the right hand side of =. It is saying that
#foo = bar || baz
is interpred as
#foo = (foo || baz)
and not
(#foo = foo) || baz

Why `TrueClass === true` evaluates to `true` but `true === TrueClass` evaluates to `false`? [duplicate]

In Ruby, what is the difference between == and ===? The RDoc says
Case Equality—For class Object,
effectively the same as calling #==,
but typically overridden by
descendents to provide meaningful
semantics in case statements.
Is #== the same as ==? And could you provide an example of when/how this is used in case statements?
The two really have nothing to do with each other. In particular, #== is the equality operator and #=== has absolutely nothing to with equality. Personally, I find it rather unfortunate that #=== looks so similar to #==, uses the equals sign and is often called the case equality operator, triple equals operator or threequals operator when it really has nothing to do with equality.
I call #=== the case subsumption operator (it's the best I could come up with, I'm open to suggestions, especially from native English speakers).
The best way to describe a === b is "if I have a drawer labeled a, does it make sense to put b in it?"
So, for example, Module#=== tests whether b.is_a?(a). If you have Integer === 2, does it make sense to put 2 in a box labeled Integer? Yes, it does. What about Integer === 'hello'? Obviously not.
Another example is Regexp#===. It tests for a match. Does it make sense to put 'hello' in a box labeled /el+/? Yes, it does.
For collections such as ranges, Range#=== is defined as a membership test: it makes sense to put an element in a box labeled with a collection if that element is in the collection.
So, that's what #=== does: it tests whether the argument can be subsumed under the receiver.
What does that have to with case expressions? Simple:
case foo
when bar
baz
end
is the same as
if bar === foo
baz
end
Yes, by #== the docs mean "the instance method == of the current object".
=== is used in case statements as such:
case obj
when x
foo
when y
bar
end
Is the same as
if x === obj
foo
elsif y === obj
bar
end
Some classes that define their own === are Range (to act like include?), Class (to act like obj.is_a?(klass)) and Regexp (to act like =~ except returning a boolean). Some classes that don't define their own === are the numeric classes and String.
So
case x
when 0
puts "Lots"
when Numeric
puts(100.0 / x)
when /^\d+$/
puts(100.0 / x.to_f)
default
raise ArgumentError, "x is not a number or numeric string"
end
is the same as
if 0 == x
puts "Lots"
elsif x.is_a? Numeric
puts(100.0 / x)
elsif x =~ /^\d+$/
puts(100.0 / x.to_f)
else
raise ArgumentError, "x is not a number or numeric string"
end
Fun fact, === is also used to match exceptions in rescue
Here is an example
class Example
def self.===(exception)
puts "Triple equals has been called."
true
end
end
raise rescue Example
# => prints "Triple equals has been called."
# => no exception raised
This is used to match system errors.
SystemCallError.=== has been defined to return true when the two have the same errno. With this system call errors with the same error number, such as Errno::EAGAIN and Errno::EWOULDBLOCK, can both be rescued by listing just one of them.

Best way to test if a variable is nil or false implicitly

I was hoping someone could help me with identifying the most idiomatic way to test if a variable is nil or false implicitly for the sake of readability.
Here is my explicit example:
if somevar.nil? # explicitly checking for nil.
puts "Its nil."
end
Is it better to write:
if !somevar # implicit
puts "Var is nil or false."
end
I really like this way:
if not somevar # implicit
puts "Var is nil or false"
end
From what I am reading, testing for nil explicitly should be avoided to some extent as its generally not needed. Most examples suggest to take action only if a variable exists. However, I want to perform an action when a variable does not exist.
Main inspiration for ditching nil came from: ruby_idioms
def truthiness(value)
if value
"truthy"
else
"falsy"
end
end
puts "nil:", truthiness(nil) # falsy
puts "false:", truthiness(false) # falsy
puts "true:", truthiness(true) # truthy
puts "[]:", truthiness([]) # truthy
puts "{}:", truthiness({}) # truthy
puts "0:", truthiness(0) # truthy
I know you know Python, so I can say that:
In Python, None, False, and empty containers such as [], {}, and even 0 are all falsy.
In Ruby, nil and false are falsy, whereas most other things are truthy, even [], {}, and 0.
I think the most idiomatic way in ruby for testing whether something is false or nil is using unless:
unless somevar
puts "Var is nil or false."
end
From the ruby style guide
Favor unless over if for negative conditions (or control flow
||).
# bad
do_something if !some_condition
# bad
do_something if not some_condition
# good
do_something unless some_condition
# another good option
some_condition || do_something
You can use defined? keyword :
defined? expression tests whether or not expression refers to anything recognizable (literal object, local variable that has been initialized, method name visible from the current scope, etc.). The return value is nil if the expression cannot be resolved. Otherwise, the return value provides information about the expression.
unless defined?(var)
#your code
end
Quick PRY to test, what the defined? returns when a variable is defined and when not :-
arup#linux-wzza:~/Ruby> pry
[1] pry(main)> defined?(x)
=> nil
[2] pry(main)> x = nil
=> nil
[3] pry(main)> defined? x
=> "local-variable"
[4] pry(main)>

Using || in arguments in Ruby?

I just saw this code:
method_name(ARGV.shift || "somefile.txt")
which basically should first evalute ARGV[0] and if it doesn't exist then read from "somefile.txt".
My question was, can the && operator be also used here, and in what situations?
Also, does this concept of "passing this or this argument" to a method in Ruby have a name?
The short answer, logical operators are going to return one of its operands based on if it's truthy or falsey. In practice, nearly everything in Ruby will evaluate to true except false or nil.
Examples:
expr1 || expr2 will return (expr1 if not falsey) or (expr2)
In other words, the first truthy value or the final operand,
expr1 && expr2 will return (expr1 if falsey) or (expr2).
In other words, the first falsey value or the final operand.
As for an actual use case, a similar example would be:
Using the && operator to check for a flag in ARGV then passing the file name.
method_name(ARGV.include?('-w') && "write_file.txt")
It should be noted that this is probably not a widely accepted practice. (see comments)
However, preferring a user supplied value over a default value, by using ||, in this manner would be.
If && is used, then the argument would be nil when there is no ARGV[0] and "somefile.txt" when there is ARGV[0]. Note that elements of ARGV, if any, would be strings, so there is no possibility of ARGV[0] being nil or false when there is an element passed.
Generally, || and && are called "(short circuit) disjunction" and "(short circuit) conjunction", respectively.
A typical use case of || is to provide a default value:
foo = potentially_falesy_value || default
A typical use case of && is to provide a value that depends on the truthness of another value:
foo = hash[:bar] && hash[:bar][:baz]
|| is using for providing default values. || returns first "true" value. "True" value -- value that is interpreted as true boolean value in ruby. So first "true" value in the chain will be as the result of the expression. && returns first "false" value. Complete analogy. But it does not have such graceful application.
Apart from the obvious Boolean operator functionality, && can be used like you could in some languages such as JavaScript:
a = cond1 && cond2 && value # a is now value if cond1 and cond2,
# else nil or false (depends on cond1 and cond2)
It's not very readable (IMHO) when assigning non-Boolean variables, but it works.
first evalute ARGV[0] and if it doesn't exist then read from "somefile.txt". My ques
You are correct. The ARGV.shift || "somefile.txt" expression will evaluate to ARGV.shift if it returns some non-falsy value, and "somefile.txt" otherwise. Some other examples:
puts nil || "foo" # => "foo"
puts "foo" || "bar" # => "foo"
puts "foo" || nil # => "foo"
puts "foo" || raise # => "foo"
# and doesn't blow up, because the 'raise'
# is never evaluated
can the && operator be also used here
Sure, but is arguably of less practical value. It might be clearer to use an if in that case:
puts foo && bar
# is the same as:
if foo
puts bar
end
# or:
puts bar if foo
does this concept of "passing this or this argument to a method in Ruby" has a name?
I'm not sure if it has any 'official' name, but I commonly see this pattern being called 'default value' or 'fallback value'.

What's the difference between equal?, eql?, ===, and ==?

I am trying to understand the difference between these four methods. I know by default that == calls the method equal? which returns true when both operands refer to exactly the same object.
=== by default also calls == which calls equal?... okay, so if all these three methods are not overridden, then I guess
===, == and equal? do exactly the same thing?
Now comes eql?. What does this do (by default)? Does it make a call to the operand's hash/id?
Why does Ruby have so many equality signs? Are they supposed to differ in semantics?
I'm going to heavily quote the Object documentation here, because I think it has some great explanations. I encourage you to read it, and also the documentation for these methods as they're overridden in other classes, like String.
Side note: if you want to try these out for yourself on different objects, use something like this:
class Object
def all_equals(o)
ops = [:==, :===, :eql?, :equal?]
Hash[ops.map(&:to_s).zip(ops.map {|s| send(s, o) })]
end
end
"a".all_equals "a" # => {"=="=>true, "==="=>true, "eql?"=>true, "equal?"=>false}
== — generic "equality"
At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.
This is the most common comparison, and thus the most fundamental place where you (as the author of a class) get to decide if two objects are "equal" or not.
=== — case equality
For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.
This is incredibly useful. Examples of things which have interesting === implementations:
Range
Regex
Proc (in Ruby 1.9)
So you can do things like:
case some_object
when /a regex/
# The regex matches
when 2..4
# some_object is in the range 2..4
when lambda {|x| some_crazy_custom_predicate }
# the lambda returned true
end
See my answer here for a neat example of how case+Regex can make code a lot cleaner. And of course, by providing your own === implementation, you can get custom case semantics.
eql? — Hash equality
The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition by aliasing eql? to their overridden == method, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:
1 == 1.0 #=> true
1.eql? 1.0 #=> false
So you're free to override this for your own uses, or you can override == and use alias :eql? :== so the two methods behave the same way.
equal? — identity comparison
Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).
This is effectively pointer comparison.
I love jtbandes answer, but since it is pretty long, I will add my own compact answer:
==, ===, eql?, equal?
are 4 comparators, ie. 4 ways to compare 2 objects, in Ruby.
As, in Ruby, all comparators (and most operators) are actually method-calls, you can change, overwrite, and define the semantics of these comparing methods yourself. However, it is important to understand, when Ruby's internal language constructs use which comparator:
== (value comparison)
Ruby uses :== everywhere to compare the values of 2 objects, eg. Hash-values:
{a: 'z'} == {a: 'Z'} # => false
{a: 1} == {a: 1.0} # => true
=== (case comparison)
Ruby uses :=== in case/when constructs. The following code snippets are logically identical:
case foo
when bar; p 'do something'
end
if bar === foo
p 'do something'
end
eql? (Hash-key comparison)
Ruby uses :eql? (in combination with the method hash) to compare Hash-keys. In most classes :eql? is identical with :==.
Knowledge about :eql? is only important, when you want to create your own special classes:
class Equ
attr_accessor :val
alias_method :initialize, :val=
def hash() self.val % 2 end
def eql?(other) self.hash == other.hash end
end
h = {Equ.new(3) => 3, Equ.new(8) => 8, Equ.new(15) => 15} #3 entries, but 2 are :eql?
h.size # => 2
h[Equ.new(27)] # => 15
Note: The commonly used Ruby-class Set also relies on Hash-key-comparison.
equal? (object identity comparison)
Ruby uses :equal? to check if two objects are identical. This method (of class BasicObject) is not supposed to be overwritten.
obj = obj2 = 'a'
obj.equal? obj2 # => true
obj.equal? obj.dup # => false
Equality operators: == and !=
The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.
"koan" == "koan" # Output: => true
The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.
"koan" != "discursive thought" # Output: => true
Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.
When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.
2 == 2.0 # Output: => true
equal?
Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.
Example:
a = "zen"
b = "zen"
a.object_id # Output: => 20139460
b.object_id # Output :=> 19972120
a.equal? b # Output: => false
In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.
Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.
a = "zen"
b = a
a.object_id # Output: => 18637360
b.object_id # Output: => 18637360
a.equal? b # Output: => true
eql?
In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.
Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).
"meditation".hash # Output: => 1396080688894079547
"meditation".hash # Output: => 1396080688894079547
"meditation".hash # Output: => 1396080688894079547
The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.
Symbol.instance_method(:hash).owner # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel
String.instance_method(:hash).owner # Output: => String
Hash.instance_method(:hash).owner # Output: => Hash
In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.
"zen".eql? "zen" # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true
In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.
2 == 2.0 # Output: => true
2.eql? 2.0 # Output: => false
2.hash == 2.0.hash # Output: => false
Case equality operator: ===
Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).
String === "zen" # Output: => true
Range === (1..2) # Output: => true
Array === [1,2,3] # Output: => true
Integer === 2 # Output: => true
The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.
2.is_a? Integer # Output: => true
2.kind_of? Integer # Output: => true
2.instance_of? Integer # Output: => false
Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.
The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:
Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true
Range Implementation of ===
When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.
(1..4) === 3 # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6 # Output: => false
("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false
Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.
Regexp Implementation of ===
Returns true if the string on the right matches the regular expression on the left.
/zen/ === "practice zazen today" # Output: => true
# is the same as
"practice zazen today"=~ /zen/
Implicit usage of the === operator on case/when statements
This operator is also used under the hood on case/when statements. That is its most common use.
minutes = 15
case minutes
when 10..20
puts "match"
else
puts "no match"
end
# Output: match
In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:
if (10..20) === minutes
puts "match"
else
puts "no match"
end
Pattern matching operators: =~ and !~
The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.
The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.
"practice zazen" =~ /zen/ # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil
:zazen =~ /zen/ # Output: => 2
:zazen =~ /discursive thought/ # Output: => nil
The implementation in the Regexp class expects a string or a symbol as an argument.
/zen/ =~ "practice zazen" # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil
In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.
puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes
Pattern-matching operators are also useful for writing shorter if statements. Example:
if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
true
end
The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.
More info is available at this blog post.
I would like to expand on the === operator.
=== is not an equality operator!
Not.
Let's get that point really across.
You might be familiar with === as an equality operator in Javascript and PHP, but this just not an equality operator in Ruby and has fundamentally different semantics.
So what does === do?
=== is the pattern matching operator!
=== matches regular expressions
=== checks range membership
=== checks being instance of a class
=== calls lambda expressions
=== sometimes checks equality, but mostly it does not
So how does this madness make sense?
Enumerable#grep uses === internally
case when statements use === internally
Fun fact, rescue uses === internally
That is why you can use regular expressions and classes and ranges and even lambda expressions in a case when statement.
Some examples
case value
when /regexp/
# value matches this regexp
when 4..10
# value is in range
when MyClass
# value is an instance of class
when ->(value) { ... }
# lambda expression returns true
when a, b, c, d
# value matches one of a through d with `===`
when *array
# value matches an element in array with `===`
when x
# values is equal to x unless x is one of the above
end
All these example work with pattern === value too, as well as with grep method.
arr = ['the', 'quick', 'brown', 'fox', 1, 1, 2, 3, 5, 8, 13]
arr.grep(/[qx]/)
# => ["quick", "fox"]
arr.grep(4..10)
# => [5, 8]
arr.grep(String)
# => ["the", "quick", "brown", "fox"]
arr.grep(1)
# => [1, 1]
Ruby exposes several different methods for handling equality:
a.equal?(b) # object identity - a and b refer to the same object
a.eql?(b) # object equivalence - a and b have the same value
a == b # object equivalence - a and b have the same value with type conversion.
Continue reading by clicking the link below, it gave me a clear summarized understanding.
https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/equality-matchers
Hope it helps others.
=== #---case equality
== #--- generic equality
both works similar but "===" even do case statements
"test" == "test" #=> true
"test" === "test" #=> true
here the difference
String === "test" #=> true
String == "test" #=> false
.eql? - This operator returns true if the receiver and argument have both the same type and equal values.
for example - 10.eql?(10.0) is false.
=== - it will test equality in case statement.
for example - (1...10) === 1 is true
== - This operator checks whether the two given operands are equal or not. If equals, it returns TRUE, Otherwise it returns FALSE.
for example - (1...10) == 1 is false
for more example click here
I wrote a simple test for all the above.
def eq(a, b)
puts "#{[a, '==', b]} : #{a == b}"
puts "#{[a, '===', b]} : #{a === b}"
puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end
eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)

Resources