Sqrt in Ruby

Find this useful? Support us: Star on GitHub 6
Category: Math | Language: Ruby

In Ruby, you can use the Math module's sqrt method to find the square root of a number. Here's an example:

# Assignment of a number for which the square root is to be calculated
number = 16

# Using the sqrt method of the Math module to get the square root
square_root = Math.sqrt(number)

# Displaying the output
puts "The square root of #{number} is #{square_root}"

Output:

The square root of 16 is 4.0

You can also find the square root of a number using the exponentiation operator, as follows:

# Assigment of number for which square root is to be calculated
number = 25

# Using exponentiation operator to get the square root
square_root = number ** 0.5

# Displaying the output
puts "The square root of #{number} is #{square_root}"

Output:

The square root of 25 is 5.0