-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmath_operator.rb
More file actions
41 lines (36 loc) · 2.02 KB
/
Copy pathmath_operator.rb
File metadata and controls
41 lines (36 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Math operator
# In Ruby, you can perform various mathematical operations using operators. Here are some of the basic math operators:
# Addition: `+`
# Subtraction: `-`
# Multiplication: `*`
# Division: `/`
# Modulo: `%` (returns the remainder of a division)
# Exponentiation: `**` (raises a number to the power of another)
# Example of math operators
a = 10
b = 5
puts "Addition: #{a + b}" # Output: Addition: 15
puts "Subtraction: #{a - b}" # Output: Subtraction: 5
puts "Multiplication: #{a * b}" # Output: Multiplication: 50
puts "Division: #{a / b}" # Output: Division: 2
puts "Modulo: #{a % b}" # Output: Modulo: 0
puts "Exponentiation: #{a ** b}" # Output: Exponentiation: 100
# Assignment operators are used to assign values to variables. The most common assignment operator is `=`, but there are also compound assignment operators that combine an arithmetic operation with assignment, such as `+=`, `-=`, `*=`, `/=`, and `%=`.
x = 10 # Assignment operator
x += 5 # Equivalent to x = x + 5
puts "After addition assignment: #{x}" # Output: After addition assignment: 15
x -= 3 # Equivalent to x = x - 3
puts "After subtraction assignment: #{x}" # Output: After subtraction assignment: 12
x *= 2 # Equivalent to x = x * 2
puts "After multiplication assignment: #{x}" # Output: After multiplication assignment: 24
x /= 4 # Equivalent to x = x / 4
puts "After division assignment: #{x}" # Output: After division assignment: 6.0
x %= 5 # Equivalent to x = x % 5
puts "After modulo assignment: #{x}" # Output: After modulo assignment: 1.0
# unary operators are used to perform operations on a single operand. The most common unary operators are `+` (unary plus) and `-` (unary minus).
y = 5
puts "Unary plus: #{+y}" # Output: Unary plus: 5
puts "Unary minus: #{-y}" # Output: Unary minus: -5
# all division in ruby will return integer except if one of the operands is a float, in that case it will return a float.
puts "Integer division: #{10 / 3}" # Output: Integer division: 3
puts "Float division: #{10 / 3.0}" # Output: Float division: 3.3333333333333335