2014-10-07 66 views
-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["+"] 

這是一個計算器程序,我想從哈希中調用+操作。

+1

你有什麼問題?你是否收到任何錯誤? – 2014-10-07 18:49:52

+0

calc.rb:24:在'執行':錯誤的參數數量(0代表1)(ArgumentError) from calc.rb:44:在'(main)' – 2014-10-07 19:00:03

+1

您是否嘗試過'calculator.execute(「+」 )'而不是'calculator.execute [「+」]'?請注意圓括號而不是方括號。 – 2014-10-07 19:01:31

回答

1
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(oper) 
    send OPERATIONS[oper.to_sym] 
    end 

    OPERATIONS = { :+ => :plusCommand } 

end 

calculator = Command.new 
calculator.storeOperandA(4) 
calculator.storeOperandB(3) 
calculator.execute("+") 

#=> 
A:4 
B:3 
7 
+0

不錯的答案,+1,一個建議:你不必創建另一個常量'OPERATIONS'而不是'def execute(oper)發送{:+ =>:plusCommand} [oper.to_sym] end'。兩個原因:1 - 常量可以在運行時修改。 2 - 常量在運行時佔用內存,因爲方法不會,並且一旦上下文不在常量不會的方法中,哈希實例就會被銷燬。 – Surya 2014-10-07 19:43:38