Content of task:
Given a string of words and numbers. Extract the expression including:
- the operator: either addition or subtraction
- the two numbers that we are operating on
Return the result of the calculation.
"Panda has 48 apples and loses 4" returns 44
"Jerry has 34 apples and gains 6" returns 40
"loses" and "gains" are the only two words describing operators.
Should be a nice little kata for you :)
Note: No fruit debts nor bitten apples = The numbers are integers and no negatives
I want to optimise so ugly code:
def calculate(string) operator = '-' if string.split(' ').include? 'loses' operator = '+' if string.split(' ').include? 'gains' sum = 0 count = 0 n1 = 0 n2 = 0 string.split(' ').map do |s| if s.to_i != 0 && s.to_i.is_a?(Numeric) if count == 0 n1 = s.to_i count += 1 else n2 = s.to_i end end end n1.method(operator).(n2) end
This code nice works(all tests was passed). But I don't want a large number of variables. Maybe have you some advice how to optimise this code? Thank you in advance.