Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions calculator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#combine all if blocks into one method
def process_operator(operation, numbers)
if operation == "add" || operation == "+"
return do_math("+", numbers[0], numbers[1])
elsif operation == "subtract" || operation == "-"
return do_math("-", numbers[0], numbers[1])
elsif operation == "multiply" || operation == "*"
return do_math("*", numbers[0], numbers[1])
elsif operation == "divide" || operation == "/"
return do_math("/", numbers[0], numbers[1])
elsif operation == "modulo" || operation == "%"
return do_math("%", numbers[0], numbers[1])
end
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the user inputs a bogus operator, your program quits silently. Instead, it would be polite to let them know what went wrong.

end


def get_number(operation)
begin
puts "What's your first number?"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like making getting a number from the user its own method - good organization.

num1 = Integer(gets.chomp)

puts "What's your second number?"
num2 = Integer(gets.chomp)

if operation == '/' && num2 == 0
puts "You can't divide by zero! Try again."
puts
get_number(operation)
else
return num1, num2
end

rescue
puts "Try again, you clown. Enter a valid number."
puts
get_number(operation)
end
end

#combine these into one method
def do_math(operation,num1, num2)
if operation == "+"
puts "#{num1} + #{num2} = #{num1+num2}"
elsif operation == "-"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This big if statement looks very similar to the one in process_operator - would it be possible to consolidate the two?

puts "#{num1} - #{num2} = #{num1-num2}"
elsif operation == '*'
puts "#{num1} * #{num2} = #{num1*num2}"
elsif operation == '/'
puts "#{num1} / #{num2} = #{num1.to_f/num2.to_f}"
else
puts "#{num1} % #{num2} = #{num1%num2}"
end
end


puts "Welcome to the command line calculator!"
puts "Would you like to add, subtract, multiply, divide, or find a modulo?"

operation = gets.chomp
numbers = get_number(operation)
process_operator(operation, numbers)

puts "Thanks for using the command line calculator!"