Skip to content

Instantly share code, notes, and snippets.

@lgranger
Created September 28, 2015 00:24
Show Gist options
  • Save lgranger/3da2d7602b53aa436bdb to your computer and use it in GitHub Desktop.
Save lgranger/3da2d7602b53aa436bdb to your computer and use it in GitHub Desktop.
# Functions for preforming calculations
def addition(first_num, second_num)
puts "#{first_num} + #{second_num} = "
puts first_num.to_i + second_num.to_i
end
def subtraction(first_num, second_num)
puts "#{first_num} - #{second_num} = "
puts first_num.to_i - second_num.to_i
end
def multiplication(first_num, second_num)
puts "#{first_num} * #{second_num} = "
puts first_num.to_i * second_num.to_i
end
def division(first_num, second_num)
puts "#{first_num} / #{second_num} = "
puts first_num.to_i / second_num.to_i
end
def modulo(first_num, second_num)
puts "#{first_num} % #{second_num} = "
puts first_num.to_i & second_num.to_i
end
puts "Let's do some math!\n\nLet's start with a number"
first_num = gets.chomp
first_num_check = first_num.to_i.to_s
while first_num_check != first_num do
puts "Oops! This calculator takes numbers only! Try again:"
print ">> "
first_num = gets.chomp
first_num_check = first_num.to_i.to_s
end
puts "you entered => #{first_num}"
puts "What what would you like to do to #{first_num}?"
operator = gets.chomp.downcase
operator_check = %w(addition subtraction multiplication modulo division add subtract multiply mod divide + - * % /)
while operator_check.include?(operator) == false do
puts "Oops! I don't know how to do that!"
puts "Try one of these operators: #{operator_check[operator_check.length-operator_check.length/3...operator_check.length].join(", ")}"
print ">> "
operator = gets.chomp.downcase
end
puts "OK! We've got #{first_num} #{operator} by what number?"
print ">> "
second_num = gets.chomp
second_num_check = second_num.to_i.to_s
while second_num != second_num_check do
puts "Oops! This calculator takes numbers only! Try again:"
print ">> "
second_num = gets.chomp
second_num_check = second_num.to_i.to_s
end
case operator
when "additon", "add", "+"
puts addition(first_num, second_num)
when "subtraction", "subtract", "-"
puts subtraction(first_num, second_num)
when "multiplication", "multiply", "*"
puts multiplication(first_num, second_num)
when "division", "divide", "/"
puts division(first_num, second_num)
when "modulo", "mod", "%"
puts modulo(first_num, second_num)
end
@kariabancroft
Copy link

Nice use of the case statement to handle your operations! I like the way the case statement blocks use methods too! nice!

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