Ruby - Calculate Square Root of a Number

1. Introduction

The square root of a number is a value that, when multiplied by itself, gives the original number. It's widely used in mathematics, physics, engineering, and many other disciplines. Ruby provides an inbuilt module named Math which has a method sqrt to calculate the square root of a given number efficiently. In this guide, we'll craft a Ruby program that prompts a user for a number and then computes its square root.

2. Program Steps

1. Initialize your Ruby development environment.

2. Ask the user to input a number.

3. Use Ruby's Math.sqrt method to calculate the square root of the given number.

4. Display the result to the user.

3. Code Program

# Prompting the user for a number
puts "Enter a number to find its square root:"
number = gets.chomp.to_f
# Calculate the square root of the provided number
square_root = Math.sqrt(number)
# Display the result
puts "The square root of #{number} is: #{square_root.round(2)}"

Output:

Enter a number to find its square root:
25
The square root of 25.0 is: 5.0

Explanation:

1. gets: Captures user input. By default, this method retrieves the input as a string.

2. chomp: Used to remove the newline character which gets appended when the user hits Enter.

3. to_f: Transforms the input string into a floating-point number, ensuring more precise calculations.

4. Math.sqrt: A method from Ruby's Math module that efficiently calculates the square root of a number.

5. round(2): Rounds the result to two decimal places for a more readable output.


Comments