Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Precedence order in ruby
3.
Examples of Precedence order in ruby
3.1.
Boolean operators
3.2.
Assignments
3.3.
Methods & boolean operators
3.4.
Blocks
3.5.
Other examples
4.
Frequently Asked Questions
4.1.
What is “eql?” Operator used for?
4.2.
What will be the output of the given code? boolean_var = 15 < 16 && 15 < 15; puts boolean_var
4.3.
Guess the operator: If Condition is true? Then value X: Otherwise value Y?
4.4.
What do you mean by the Symbol in Ruby?
4.5.
Which operator is used to check variable and method are defined or not?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Operator Precedence in Ruby

Author SAURABH ANAND
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In a programming language, the sequence of math operations is important. If we don't know them well, we may get utterly unexpected results. And our code could be absolutely incorrect.

We must understand the rules. Is the order similar to that of math? Or is the algebraic expression translated from left to right? Do we know how this appears in Ruby? Let's have a look.

2 + 2 * 2

 => 6

Yes, it’s 6 and not 8. As the precedence of * (multiplication) is more than + (addition), we will learn more about precedence in this blog, so keep reading.

Precedence order in ruby

Operator precedence in Ruby determines the grouping of terms in an expression. It decides how an expression is evaluated. Certain operators in Ruby have higher precedence than others.
Let us see the precedence order of operators in Ruby.

Precedence order in ruby

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples of Precedence order in ruby

Let’s see some most common examples of Precedence order in ruby.

Boolean operators

Let's start with the basics. Precedence hierarchy for boolean operators.

puts (1 || 2 && nil)
puts (1 or 2 and nil)

 

Output:

1
Nil

 

The logic appears to be the same, yet the results are not. However, if we look closely, we will see a difference in the order of the calculations. The order in the first case is (1 || (2 && nil)). From 2 && nil, we get nil. Then we have 1 || nil, which equals 1. Our interpreter is far smarter than you may imagined. Because of the || operator. It has always been true when the left-hand side is true, therefore it just verifies the first part of our phrase.

Assignments

This example is related to boolean operators, but also to assignment:

puts (fox = 1 and 2)

 

Output: 

2

 

Or

fox = 1 && 2
puts fox

Output: 

2

 

Both of these logic formulations yield a truthy outcome of 2. But there is one distinction here. In the first situation, foo = 2, but in the second case, foo equals 1. This is, of course, connected to operator precedence. Because && takes precedence over =.

Methods & boolean operators

We're still in the domain of boolean operators. This example will demonstrate how they act with method calls when no brackets are specified. In Ruby, we can, as we know, omit brackets in some circumstances. However, we must exercise caution when working with boolean at the same time.

# Declare method
def method(char)
puts "My char id #{char}"
end

# Example
method 'a' || 'b'

 

Output:

My char id a
nil

 

In this case, the first operator || will be called. We'll get an 'a' out of it. This is why we see the sentence "My character id a." However, because the method simply displays the test and does not return anything, we see a nil value at the end. It is essential that our method always returns nil.

Blocks

It's time for blocks. We must remember that blocks with have higher precedence than blocks do... end. This is not explicitly stated in our order table, but there is a short mention about it in the documentation. So, let's have a look at this. We'll make two techniques out of blocks. In the first, we'll call the block with {}, and in the second, we'll call it do... end.

def fox(options = {}, &block)
puts "fox has block: #{block_given?}"
end

def bar(options = {}, &block)
puts "Bar has block: #{block_given?}"
end

fox a: bar { 1 }
fox a: bar do 1 end

 

Output:

Bar has block: true
fox has block: false
Bar has block: false
fox has block: true

 

In Example 1, the order is as follows: fox(a: (bar {1} )). First, we'll use a block to call the bar method. It will return nil, and we will then invoke method fox with only the hash parameter. It will seem as follows: fox (a: nil). As a result, we don't get a block in method fox.

The order is reversed in the second example: fox(a: bar) do 1 end. It will be even better if it is divided into distinct lines.

Other examples

Let us see some examples.

Example 1

array = []
a = 1
b = 2
array << a + b
puts array

 

Output:

3

 

This example behaves as expected. it started by adding a and b, and then we add value to the array. If you look at our precedence table, + takes precedence over.

 

Example 2

a = 1
b = 2
sum = 0
multi = 1

sum += a + b
puts sum

multi *= a * b
puts multi

 

Output:

3
2

 

Everything will be fine in this case as well. += and *= take precedence over + and *.

 

Example 3

n = 9
1..n - 1
puts (1..n - 1).to_a
Output:
1
2
3
4
5
6
7
8

 

In this example, to_a converts the numbers generated by 1..n-1 into an array

Frequently Asked Questions

What is “eql?” Operator used for?

eql? Return True if the receiver and argument have both the same type and equal values.

What will be the output of the given code? boolean_var = 15 < 16 && 15 < 15; puts boolean_var

False, as 15<16 is true but 15<15 is false hence the overall expression will evaluate as false.

Guess the operator: If Condition is true? Then value X: Otherwise value Y?

The ternary operator first evaluates the expression for a true or false value and then Ternary Operator executes one of the two given statements depending upon the result of the evaluation.

What do you mean by the Symbol in Ruby?

The most basic Ruby object we can make is a symbol. It's nothing more than a name and an internal ID. Symbols are more useful and efficient than strings because they refer to the same object throughout a Ruby program.

Which operator is used to check variable and method are defined or not?

defined? is a special operator that takes the form of a method call to determine whether or not the passed expression is defined.

Conclusion

In this article, we have extensively discussed the concept of the Operator Precedence in Ruby. We started with the introduction of Operator Precedence in Ruby, various Operator Precedence in Ruby, and concluded with examples of Operator Precedence in Ruby.

After reading about the Operator Precedence in Ruby, are you not feeling excited to read/explore more articles on the topic of ruby? Don't worry; Coding Ninjas has you covered. To learn, see Iterating Strings in RubyConstants in Ruby, and Hashes in Ruby.

 Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your capacity in coding, you may check out the mock test series and participate in the contests hosted on the Coding Ninjas Studio website. But if you have just started learning and are looking for questions asked by tech giants like Amazon, Microsoft, Google, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

You may also consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

thank you image

Previous article
Operator overloading in Ruby
Next article
Introduction to Expressions and Operators in Ruby
Live masterclass