如何从Hash调用方法?

时间:2014-10-07 18:47:06

标签: ruby

它是一个计算器程序,我想从Hash调用+操作。

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["+"]

它是一个计算器程序,我想从Hash调用+操作。

1 个答案:

答案 0 :(得分: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