Ruby - Calculate the Sum of Two Numbers

1. Introduction

Calculating the sum of two numbers is a foundational concept in programming and serves as a great introduction to the Ruby language for beginners. This simple task helps in understanding user input, variable usage, and output display. Let's walk through a Ruby program that accomplishes this.

2. Program Steps

1. Start your Ruby development environment.

2. Prompt the user to input two numbers.

3. Convert the user input from string format to an integer or floating point, depending on the requirement.

4. Calculate the sum of the two numbers.

5. Display the result to the user.

3. Code Program

# Prompting the user for the first number
puts "Enter the first number:"
num1 = gets.chomp.to_f
# Prompting the user for the second number
puts "Enter the second number:"
num2 = gets.chomp.to_f
# Calculating the sum of the two numbers
sum = num1 + num2
# Displaying the result
puts "The sum of #{num1} and #{num2} is: #{sum}"


Enter the first number:
Enter the second number:
The sum of 5.5 and 6.5 is: 12.0


1. puts: This method is used to display messages to the console. It is used here to prompt the user to enter numbers.

2. gets: This is used to get user input. By default, it reads the input as a string.

3. chomp: This method is applied to the string input to remove the newline character (which is added when the user presses Enter).

4. to_f: This method converts a string to a floating-point number. If you're only working with integers, you could use to_i instead.

5. sum = num1 + num2: This line calculates the sum of the two numbers provided by the user.