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.