Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to get the power of a number in Ruby

okwudili onyejiaku

Overview

We can easily get the power of a number in Ruby without using any inbuilt methods. All we need to do is create a for loop that will run from 1 to n, where n is the specified power.

Syntax

for counter in 1..power 
    result = result * number
end
Get the power of a number in Ruby
  • counter: This is the counter that we will use in the loop.
  • power: This is the specified power.

Code

# create a function to get the power of a number
def getPower(number, power)
  # set default value for result
  result = 1
  for counter in 1..power
    result = result * number
  end
  return result
end

# declare and initialize variables
num1 = 2
num2 = 10
num3 = -3
num4 = 50

# get powers of some numbers
puts getPower(num1, 2)   # 4
puts getPower(num2, 10)  # 10000000000
puts getPower(num3, 1)   # -3
puts getPower(num4, 5)   # 312500000
Getting the power of some numbers in Ruby

Explanation

  • Line 2: We create a function that will return the power of any number specified. It takes two parameters, number and power.
  • Lines 12–15: We declare and initialize some number variables.
  • Lines 18–21: We invoke the method and print the results.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring