-2
這是一個計算器程序,我想從哈希中調用+操作。如何從哈希中調用方法?
class Command
def storeOperandA(a)
puts "A:" + a.to_s
@a = a
end
def storeOperandB(b)
puts "B:" + b.to_s
@b = b
end
def plusCommand
result = @a + @b
puts result
end
def minusCommand
result = @a - @b
puts result
end
def execute(operation)
@operation = operation
if operation == "+"
self.plusCommand
elsif operation == "-"
self.minusCommand
end
end
operations = { :+ => plusCommand }
end
calculator = Command.new
calculator.storeOperandA(4)
calculator.storeOperandB(3)
calculator.execute["+"]
這是一個計算器程序,我想從哈希中調用+操作。
你有什麼問題?你是否收到任何錯誤? – 2014-10-07 18:49:52
calc.rb:24:在'執行':錯誤的參數數量(0代表1)(ArgumentError) from calc.rb:44:在'(main)' – 2014-10-07 19:00:03
您是否嘗試過'calculator.execute(「+」 )'而不是'calculator.execute [「+」]'?請注意圓括號而不是方括號。 – 2014-10-07 19:01:31