DEV Community

Jess Lee
Jess Lee

Posted on • Updated on

What does ** (two asterisks in a row) mean in Ruby?

Today I saw ** used between two integers. I had no idea what it meant so I turned to google. Turns out that two asterisks is Ruby's arithmetic operator for exponentiation.

i.e. 2**3 means 2³ aka 2x2x2 aka 8

Top comments (3)

val_baca profile image
Valentin Baca • Edited

I used to do Project Euler in college with Ruby during semesters when I had fewer coding classes, and this brings back memories!

Don't forget about irb and ri:

$ irb
irb(main):001:0> help 'Integer#**'
# or
$ ri 'Integer#**'

Both give:

= Integer#**

(from ruby core)
  int ** numeric  ->  numeric_result


Raises int to the power of numeric, which may be negative or fractional. The
result may be an Integer, a Float, a Rational, or a complex number.

  2 ** 3        #=> 8
  2 ** -1       #=> (1/2)
  2 ** 0.5      #=> 1.4142135623730951
  (-1) ** 0.5   #=> (0.0+1.0i)

  123456789 ** 2     #=> 15241578750190521
  123456789 ** 1.2   #=> 5126464716.0993185
  123456789 ** -2    #=> (1/15241578750190521)

Useful since google can be a little hard to use with special characters, like "**"

jballanc profile image
Joshua Ballanco • Edited

Ah yes...exponentiation. There's a mildly interesting (mostly annoying) history around the choice of operator for it. Back in the good ol' days of C, it was much more common to find oneself twiddling bits than doing higher order math. A very useful operation if you are dealing with bits is the bit-wise XOR. In mathematics, this operation is usually represented with the character. However, since this is not part of the base ASCII set of characters, the developers of C chose to use the next closest thing: ^.

Of course, when more feature-full languages such as Perl came along and wanted to have an operator for exponentiation, they were stuck. While ^ is typically used in mathematics for this operation, C already established the tradition of using this for XOR. Thus was ** born. Ruby, Python, Javascript, and a whole host of other languages followed suit.

But not Julia. Julia made two decisions early on in its development. First, Julia is very mathematics focused and tries to keep as close to traditional conventions from mathematics as possible. Second, Julia (like Swift and many other languages today) embraced the full unicode set for operators. Julia also made it easy to use these operators by allowing one to type \xor at the REPL, hit <TAB>, et voila:

julia> 2 ^ 3
julia> 2  3
_swanand profile image
Swanand • Edited

It is also called double-splat operator, and can be used to apply named arguments to a method:

def add_name(first_name:, middle_name: nil, last_name:)
  pp [first_name, middle_name, last_name]
  # other code here

name_attributes = { first_name: "Mickey", last_name: "Mouse" }


# => ["Mickey", nil, "Mouse"]

Enter fullscreen mode Exit fullscreen mode