Skip to content

Instantly share code, notes, and snippets.

@kdefliese
Created September 28, 2015 01:33
Show Gist options
  • Save kdefliese/d62d46fe338548375553 to your computer and use it in GitHub Desktop.
Save kdefliese/d62d46fe338548375553 to your computer and use it in GitHub Desktop.
Calculator exercise from 9/25 class
puts "Hello! We are going to calculate some numbers today. Enter a number:"
num1 = gets.chomp
while num1.to_f.to_s != num1 && num1.to_i.to_s != num1
puts "That's not a number!"
puts "Try again and enter a number:"
num1 = gets.chomp
end
puts "Great! Now enter another number:"
num2 = gets.chomp
while num2.to_f.to_s != num2 && num2.to_i.to_s != num2
puts "That's not a number!"
puts "Try again and enter a number:"
num2 = gets.chomp
end
if num1.include? "."
num1 = num1.to_f
num2 = num2.to_f
elsif num2.include? "."
num1 = num1.to_f
num2 = num2.to_f
else
num1 = num1.to_i
num2 = num2.to_i
end
puts "Ok, what kind of math would you like to do?"
operation = gets.chomp
if operation == "+" || operation == "add" || operation == "addition"
total = num1 + num2
puts "#{num1} + #{num2} = #{total} \nYour total is #{total}"
elsif operation == "-" || operation == "subtract" || operation == "subtraction"
total = num1 - num2
puts "#{num1} - #{num2} = #{total} \nYour total is #{total}"
elsif operation == "*" || operation == "multiply" || operation == "multiplication"
total = num1 * num2
puts "#{num1} * #{num2} = #{total} \nYour total is #{total}"
elsif operation == "/" || operation == "divide" || operation == "division"
if num1 % num2 == 0
total = num1 / num2
puts "#{num1} / #{num2} = #{total} \nYour total is #{total}"
else
total = num1.to_f / num2.to_f
puts "#{num1} / #{num2} = #{total} \nYour total is #{total}"
end
elsif operation == "^" || operation == "exponent" || operation == "exponents"
total = num1 ** num2
puts "#{num1}^#{num2} = #{total} \nYour total is #{total}"
elsif operation == "%" || operation == "modulus" || operation == "modulo"
total = num1 % num2
puts "#{num1} % #{num2} = #{total} \nYour total is #{total}"
else
puts "Not a valid operation! Sorry, please try again."
end
@kariabancroft
Copy link

In your conditional from lines 17-26, could you simplify the first two conditionals to use an or rather than using the same content. i.e.:

if num1.include? "." || num2.include? "."
  num1 = num1.to_f
  num2 = num2.to_f
else
  num1 = num1.to_i
  num2 = num2.to_i
end

@kariabancroft
Copy link

I like the way you're using a single puts statement with a \n to have two lines of output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment