Created
May 14, 2015 04:27
-
-
Save falonofthetower/dbbc14e0794362f91fa0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# If instead of monkey patching it you do it this way you don't lose anything | |
def is_valid_expression?(expression) | |
regexp = / | |
\A\d+\.?\d* # any number that contains only one decimal | |
\s+ # white space after first number and before operand | |
[\+\/\-\*] # matches available operands | |
\s+ # white space after first number and before operand | |
\d+\.?\d*$ # any number that contains only one decimal | |
/x | |
# ruby has explicit return so the final line is returned | |
(expression =~ regexp) == nil ? false : true | |
end | |
def display_intro_msg | |
puts "=> Simple Calculator Rules:" \ | |
"\n * Currently only supports calculations on two digits" \ | |
"\n * Please include spaces before and after operand" \ | |
"\n * Integers can contain decimals" \ | |
"\n * valid operators: +, /, -, *" \ | |
"\n * Press [Ctrl + c] anytime to exit" | |
end | |
def calculate(expression) | |
expression = expression.split() | |
values = [expression[0].to_f, expression[2].to_f] | |
operator = expression[1].to_sym | |
solution = values.inject(operator) | |
puts "=> Solution: #{solution.round(2)}\n\n" | |
end | |
def get_user_expression | |
puts "\nPlease Enter expression: e.g(1 + 2 or 2.3 / 4.5)" | |
gets.chomp | |
end | |
def get_user_expression | |
puts "\nPlease Enter expression: e.g(1 + 2 or 2.3 / 4.5)" | |
gets.chomp | |
end | |
display_intro_msg | |
error_message = "ERROR: not a valid expression, must include" \ | |
" spaces before and after operator!" \ | |
"\n e.g(1 + 5 or 2 / 5)\n\n" | |
# if/else is a better fit for this | |
loop do | |
expression = get_user_expression | |
if is_valid_expression?(expression) | |
calculate(expression) | |
else | |
puts error_message | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment