Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Easy

Expressions and Operators in Ruby

Author Sanchit Kumar
1 upvote
gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

An expression is a section of Ruby code that the Ruby interpreter can evaluate to produce a value. An operator is a token or a particular symbol in the Ruby language representing an operation (such as addition or comparison) performed on one or more operands. 

The operands are expressions, and operators allow us to combine these operand expressions into more significant expressions. The numeric literal 2 and the operator +, for example, can be integrated into the expression 2+2. Mathematical operators are used in programming languages. Data is processed using the operators. An operand is one of an operator's inputs (arguments).

Sample expressions: 

  • # A numeric literal
    6
     
  • # A local variable reference
    x       
                                   
  • # A method invocation
    Math.sqrt(9)        
                
  • # Assignment
    x = Math.sqrt(9)    
             
  • # Multiplication with the * operator
    9*9                                 

 

With operators like the assignment operator and the multiplication operator, primary expressions like literals, variable references, and method invocations can be joined into more significant expressions.

Expressions and Operators

Ruby's syntax is expression-oriented. In Ruby, if control structures that would be considered statements in other languages are known as expressions. They contain values in the same way that other simpler expressions do.

Despite the fact that all statements in Ruby are expressions, not all of them return valid values. For example, while loops and method definitions are expressions that return nil value typically.

Like most other languages, Expressions in Ruby are typically composed of values and operators. Anyone who has worked with C, Java, JavaScript, or another programming language will be familiar with Ruby's operators.

Here are examples of some commonplace and some more unusual Ruby operators:

  • 1 + 2
    # => 3: addition 
     
  • 1 * 6
    # => 6: multiplication 
     
  • 1 + 8 == 9
    # => true: == tests equality 
     
  • 2 ** 1024
    # 2 to the power 1024: arbitrary size ints 
     
  • "Ruby" + " rocks!"
    # => "Ruby rocks!": string concatenation 
     
  • "Ruby! " * 2
    # => "Ruby! Ruby! ": string repetition 
     
  • "%d %s" % [3, "rubies"]
    # => "3 Rubies": Python-style, printf formatting 
     
  • max = x > y ? x : y
    # Conditional operator

 

Many Ruby operators are implemented as methods, which can be defined (or redefined) by classes. (They cannot define entirely new operators; there is only a fixed set of recognised operators.)

Consider how the + and * operators behave differently for integers and strings. In your own classes, you can define these operators however you want.

Another good example is the << operator. Following the C programming language, the integer classes Fixnum and Bignum use this operator for the bitwise left-shift operation. Simultaneously (as in C++), other classes, such as strings, arrays, and streams, use this operator for append operations. It is a good idea to define << if you are creating a new class that can have values appended to it in some way.

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

Code Implementation

Let us see an example to understand expressions and operators in Ruby.

a = 3
b = 6
c = 9

puts a + b + c
puts c - a
puts a * b
puts c / 3
puts c % a
puts c ** a
puts Math.sqrt(9)
puts 1 + 8 == 9
puts "Ruby" + " rocks!"
puts "Ruby! " * 2
puts "Ruby " + "is " + "Programmer's " + "Homie"
puts 3 << 1
puts 18 >> 1

 

Output

18
6
18
3
0
729
3.0
true
Ruby rocks!
Ruby! Ruby! 
Ruby is Programmer's Homie
6
9

Ruby Surprises

Every language has features that trip up programmers who are new to the language. Two of Ruby's surprising features:

Strings in Ruby are mutable, which may surprise Java programmers in particular. You can use the []= operator to change the characters in a string or to insert, delete, and replace substrings. The << operator appends to a string, and the String class defines a number of other methods for modifying strings in place. String-literals in a program are not unique objects because they are mutable.

Code Implementation

s = "Coding"
s << " Ninjas."
puts s

 

Output

Coding Ninjas.

 

Read about Bitwise Operators in C here.

Frequently Asked Questions

What is Ruby?

Ruby is a high-level-interpreted programming language that supports a wide range of programming paradigms. It was designed with programming productivity and ease of usage in mind.

What is the difference between Statement and Expression in Ruby?

An expression is a type of statement. All expressions are statements, but not all statements are expressions. There is a difference: c if n is a statement, but (c if n) becomes an expression. The consequence is that puts(c if n) will result in SyntaxError, but puts((c if n)) will not give SyntaxError because method arguments must be expressions.

How to show Ruby's flexibility using operators?

Ruby is a flexible language since it allows users to modify its components freely. The plus (+) operator, for example, is used to execute addition. However, if you prefer to use the more readable word plus, you may add a method to Ruby's Numeric class.

What is an immutable object?

Object whose state cannot be changed after it has been created is called an immutable object. Because immutable objects' states cannot be changed, it makes no sense to duplicate the same object. In fact, with Ruby 2.3 (with frozen strings enabled), each string-literal value used in the program has its own instance.

Are strings in Ruby mutable?

In most languages, string literals are also immutable, just like numbers and symbols. In Ruby, however, all strings are mutable by default. [Immutable String-literal with Ruby 3]

Conclusion

This article extensively discussed the Expressions and Operators in Ruby. We started with a brief introduction about expressions, operators and how expressions are built out of values and operators.

After reading about the Expressions and Operators in Ruby, are you not feeling excited to read/explore more articles on the topics related to Ruby? Don't worry; Coding Ninjas has you covered. To learn, see History of Ruby8 reasons why Ruby should be your first languageDocumentation of Ruby, and Ruby vs Python.

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 competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may 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!

Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass