Raise a value to a negative power in Ruby

I ran into a few kinks trying to raise some numbers to a negative power in Ruby. Ruby uses the ** operator for exponential calculations. Here’s the little hiccup I encountered:

# 2^2 = 4
# here is the IRB dump
>> 2**-2
=> Rational(1, 4)

# but I don't want the actual number!
>> (2**-2).to_f
=> 0.25

Tags:

Leave a comment