iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 29
0
自我挑戰組

自我挑戰 Ruby 刷題 30 天系列 第 29

Day29 - Codewars 刷題

挑戰 Codewars LV3 題目


題目(Calculator)

Create a simple calculator that given a string of operators (), +, -, *, / and numbers separated by spaces returns the value of that expression

Example:

Calculator.new.evaluate("2 / 2 + 3 * 4 - 6") # => 7
Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.
class Calculator
  def evaluate(string)
  end
end

calc = Calculator.new

Test.assert_equals(calc.evaluate("4 + 5"), 9)
Test.assert_equals(calc.evaluate("4 * 5"), 20)
Test.assert_equals(calc.evaluate("4 / 5"), 0.8)
Test.assert_equals(calc.evaluate("4 - 5"), -1)
Test.assert_equals(calc.evaluate("4 + 5 * 6"), 34)

影片解題:


答案:

# Calculator
class Calculator
  def evaluate(string)
    ['+', '-', '*', '/'].each do |cal|
      if string.include?(cal)
        return string.split(cal).map{ |x| evaluate(x) }.inject(cal.strip)
      end
    end
    string.to_f
  end
end

本文同步發布於 小菜的 Blog https://riverye.com/


上一篇
Day28 - Codewars 刷題
下一篇
Day30-完賽是這種感覺啊
系列文
自我挑戰 Ruby 刷題 30 天31

尚未有邦友留言

立即登入留言