What Does ** Do in Ruby?

In Ruby, "**" represents the exponentiation operator, which returns the result of raising the first operand to the power of the second operand.

For example, the mathematical expression 2 ^ 5 (i.e. two raised to the power of five) can be expressed using the exponentiation operator in the following way:

puts 2 ** 5 #=> 32

In this case, 2 is the base and 5 is the exponent.

This is the same as using the Integer#pow method:

puts 2.pow(5) #=> 32

Using either, the exponential operator (**) or the Integer#pow method, is merely a shorter form of multiplying the base number as many times to itself as denoted by the exponent. For example, consider the following, which is equivalent to the examples above:

puts 2 * 2 * 2 * 2 * 2 #=> 32

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.