Ruby中的简单计算器DSL

时间:2014-06-25 10:57:44

标签: ruby dsl

我在Ruby中实现计算器DSL。代码如下。这给了我一个错误,说明' +'总计=总数+数字未定义。可能是什么错误?另外,导致它的初始化函数是否有任何问题?

class Calculator 
attr_accessor :total

def initialize(&block)
    self.total = 0
    instance_eval(&block)
    return total
end

def add(number)
     total = total + number
end

def subtract(number)
    total -= number
end

def multiply(number)
    total *= number
end

def divide(number)
    total /= number
end
end

h = Calculator.new do
  add 3
  add 5
end

错误消息是 -

  calculator_dsl.rb:10:in `add': undefined method `+' for nil:NilClass (NoMethodError)
from calculator_dsl.rb:27:in `block in <main>'
from calculator_dsl.rb:5:in `instance_eval'
from calculator_dsl.rb:5:in `initialize'
from calculator_dsl.rb:26:in `new'
from calculator_dsl.rb:26:in `<main>'

1 个答案:

答案 0 :(得分:4)

简答:名称冲突(局部变量与方法)

答案很长:

def add(number)
  puts defined?(total)
  total = (puts defined?(total); total + number)
end

此代码输出

method
local-variable
NoMethodError: undefined method `+' for nil:NilClass

就在这一行之前

 total = total + number

创建一个新的局部变量total,它从外部范围隐藏方法。它也设置为nil,它解释了你得到的错误。

为避免创建新的本地var,请使用self

 self.total = total + number
 # or
 self.total += number