w3resource

Ruby Arithmetic Operators

Arithmetic Operators

Arithmetic operators take numerical values as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).

Operator Name Example Result
+ Addition x+y Sum of x and y.
- Subtraction x-y Difference of x and y.
* Multiplication x*y Product of x and y.
/ Division x/y Quotient of x and y.
% Modulus x%y Remainder of x divided by y.
** Exponent x**y x**y will give x to the power y

Example: Ruby arithmetic operator

puts ("add operator") 
 puts(5 + 6)    
 puts ("subtract operator")
 puts(10 - 4)    
 puts ("multiply operator")
 puts(5 * 6)    
 puts ("divide operator")
 puts(15 / 3)   
 puts ("raise to a power operator")
 puts(15**2)    
 puts ("modulo operator")
 puts(14 % 5) 

Output:

add operator
11
subtract operator
6
multiply operator
30
divide operator
5
raise to a power operator
225
modulo operator
4

More examples on Ruby division operator:

 puts ("division in Ruby")
 puts ("both operand are integer")
 puts 34 / 2       
 puts ("both operand are integer, truncation")
 puts 35/ 2      
 puts ("at least one operand is float")
 puts 35.0 / 2    
 puts ("both operand are float")
 puts 35.0 / 2.0  

Output:

division in Ruby
both operand are integer
17
both operand are integer, truncation
17
at least one operand is float
17.5
both operand are float
17.5

Unary operators:

puts +4 + -2
puts -12 + 22
puts -10 - +3
puts 12 * -7 

Output:

2
10
-13
-84

Previous: Ruby Operators Precedence
Next: Ruby Comparison Operators



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/ruby/ruby-arithmetic-operators.php