Building a simple calculator in Ruby Language
Ruby is a fantastic programming language, it is server-side, can be embedded into HTML and is a pure Object-Oriented language. I am going to write a small program, a simple calculator to demonstrate it’s might. You would probably require Ruby lang in your system to run this code, alternatively, you can use Repl (https://repl.it/), which is an excellent cloud-based IDE, do check it out! Now let’s get started!
Note: I have added all the relevant instructions as comments in the code.
The Code:
# You use ‘puts’ when you want to print something with the newline
puts 'Simple Calculator'
# This is like a quick loop, it will print “-” 20 times
# We print here, because we don’t a new line with every hyphen
20.times { print "-" }
# Empty puts creates a newline
puts
# Get the first number
puts "What is your first number?"
# gets.chomp simply gets an input from user and preserve it in a variable
num1 = gets.chomp
# Get the second number
puts "What is your second number?"
num2 = gets.chomp
# We are simply asking user to give us one number, so
# we can determine which operation we need to perform.
puts "Which operations needs to be performed? Type number:"
puts "1. +"
puts "2. -"
puts "3. *"
puts "4. /"
puts "5. % (Modulus)"
operator = gets.chomp
# Bunch of ifs, elsifs to correctly operate based on user selection.
# If nothing matches, program will do addition
if operator == "2"
result = num1.to_f - num2.to_f
elsif operator == "3"
result = num1.to_f * num2.to_f
elsif operator == "4"
result = num1.to_f / num2.to_f
elsif operator == "5"
result = num1.to_f % num2.to_f
else
result = num1.to_f + num2.to_f
end
# Finally we output the result to the user
puts "Your result: #{result}"And that’s how simple it is to make a functional calculator in Ruby programming language!
