3

What is ** operator in Ruby?

Code snippet

1 ** 5 # => 1
43 ** 67 # => 27694053307656599023809257877241042019569010395053468294153499816223586030238186389799480520831161107426185107
Gupta
  • 8,882
  • 4
  • 49
  • 59

5 Answers5

13

In Ruby, ** is the exponent operator. I.e., by doing a**b, you are raising a to the power of b. By convention, there are no spaces between the operands.

Example:

3**2
#=> 9

2**3
#=> 8

Note that the exponent operator has a higher precedence than multiplication and division, just like in mathematics:

2 * 2**3 # (2 * 8)
#=> 16

18 / 3**2 # (18 / 9)
#=> 2

If you chain the operator, precedence is resolved from the right to the left:

2**2**3 == 2**(2**3) # (2^8)
#=> true
Drenmi
  • 8,492
  • 4
  • 42
  • 51
4

It's a power math operator:

2 * 3
# => 6

but

2 ** 3
# => 8
Paweł Dawczak
  • 9,519
  • 2
  • 24
  • 37
4

** is Exponent Operator- It performs exponential (power) calculation. Let me explain by this simple example

2 ** 2 => 2 * 2 => 4

2 ** 3 => 2 * 2 * 2 => 8

2 ** 4 => 2 * 2 * 2 * 2 => 16

2 ** 5 => 2 * 2 * 2 * 2 * 2 => 32

so 43 ** 67 => 43 * 43 * 43 * 43 ...............................................................

so it results in such a big number.

To get more details on operatorts http://www.tutorialspoint.com/ruby/ruby_operators.htm

Shahzad Tariq
  • 2,767
  • 1
  • 22
  • 31
2

** Exponent - Performs exponential (power) calculation on operators

1 ** 5 = 1 

Means it will execute like 1*1*1*1*1 five times

If you will try this

2**4 = 16

Means it will execute like 2*2*2*2 four times

rick
  • 1,675
  • 3
  • 15
  • 28
1

Its just do it as:

2 * 4 => 8

and

2 ** 4 => 64 

It treat as power of 2 as (2)^4 => 2*2*2*2

Gaurav Gupta
  • 475
  • 4
  • 11