Operators are symbols or keywords in Ruby that allow you to perform various operations on values and variables. In this section, we'll explain the different types of operators in Ruby and how to use them in your code.
.jpg)
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on numbers. The following table lists the arithmetic operators available in Ruby:
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo (remainder) |
** | Exponentiation |
Here's an example of using arithmetic operators in Ruby:
x = 5 y = 3 puts x + y # Output: 8 puts x - y # Output: 2 puts x * y # Output: 15 puts x / y # Output: 1 (Note: this is integer division) puts x % y # Output: 2 puts x ** y # Output: 125
Comparison Operators
Comparison operators are used to compare two values and return a boolean value (true or false). The following table lists the comparison operators available in Ruby:
Operator | Description |
---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
Here's an example of using comparison operators in Ruby:
x = 5 y = 3 puts x == y # Output: false puts x != y # Output: true puts x < y # Output: false puts x > y # Output: true puts x <= y # Output: false puts x >= y # Output: true
Logical Operators
Logical operators are used to combine boolean expressions and return a boolean value. The following table lists the logical operators available in Ruby:
Operator | Description |
---|---|
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
Here's an example of using logical operators in Ruby:
x = 5 y = 3 z = 7 puts (x > y) && (z > y) # Output: true puts (x > y) || (z < y) # Output: true puts !(x > y) # Output: false
Assignment Operators
Assignment operators are used to assign a value to a variable. The following table lists the assignment operators available in Ruby:
Operator | Description |
---|---|
= | Simple assignment |
+= | Addition assignment |
-= | Subtraction assignment |
*= | Multiplication assignment |
/= | Division assignment |
%= | Modulo assignment |
**= | Exponentiation assignment |
Here's an example of using assignment operators in Ruby:
x = 5 x += 2 # Equivalent to: x = x + 2 puts x # Output: 7 y = 10 y /= 3 # Equivalent to: y = y / 3 puts y # Output: 3
Conclusion
Operators are essential in Ruby programming and are used to perform various operations on values and variables. By understanding the different types of operators available in Ruby and how to use them in your code, you can write more expressive and powerful programs.
0 Comments