Levy Shi
Levy Shi

Reputation: 29

I'm new to programming and would like to know how to create a calculator using ruby

Here is my current code for the calculator but I don't know how to make the two numbers perform the operation.

#calculator
#ask the user for the first number
puts "Please select your first number"
#store num_1 inside a variable
num_1 = gets.chomp.to_i
#spit back the number
puts "#{num_1}"
#ask the user what order of operation they want to use
puts "would you like to add, subtract, multiply, or divide this number?"
#store the order of operation inside a variable
operation = gets.chomp.to_i
#ask the user for a second number
puts "please select a second number to #{operation}"
#store num_2 inside a variable
num_2 = gets.chomp.to_i
#perform the task and spit out a number
answer = num_1 operation num_2
#spit out the number
puts "your answer for #{num_1} #{operation} #{num_2} = #{answer}"

Upvotes: 1

Views: 55

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

You almost there. In your case you need to call public_send method to perform the desired operation.

answer = num_1.public_send operation, num_2

Note: operation = gets.chomp.to_i should be operation = gets.chomp.

As per your code add, subtract, multiply, or divide will be +, -, * and / respectively. Now as you are using gest method to take those as an input, you will be getting '+', '-' etc after chomping. Now if you call String#to_i method on those "+", "-" etc, as per the documentation,

If there is not a valid number at the start of str, 0 is returned.

Read about public_send.

Upvotes: 2

Related Questions