Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby中可变作用域对DSL的干扰_Ruby - Fatal编程技术网

Ruby中可变作用域对DSL的干扰

Ruby中可变作用域对DSL的干扰,ruby,Ruby,Ruby返回此错误,因为它知道new\u age是在方法参数中定义的局部变量。因此,当我将Person类更改为: module Typecast class DSL def self.call(&blk) new.instance_eval(&blk) end def new_age(val) p val end end def typecast(&blk) DSL.call(&blk)

Ruby返回此错误,因为它知道
new\u age
是在方法参数中定义的局部变量。因此,当我将
Person
类更改为:

module Typecast
  class DSL
    def self.call(&blk)
      new.instance_eval(&blk)
    end
    def new_age(val)
      p val
    end
  end

  def typecast(&blk)
    DSL.call(&blk)
  end
  private :typecast
end

class Person
  include Typecast
  def age=(new_age)
    typecast do
      new_age :integer
    end
  end
end

Person.new.age = 10

# test.rb:33: syntax error, unexpected ':', expecting keyword_end
#       new_age :integer
Ruby现在返回预期的
:整数


我的问题是,如何阻止局部变量干扰
实例_eval
块?

当一个变量和一个名称相同的方法都存在于同一范围内时,消除歧义的方法是澄清接收者。在这种情况下,您希望接收器是
self

class Person
  include Typecast
  def age=(new_val)
    typecast do
      new_age :integer
    end
  end
end

是的,我知道这件事。我想知道是否有办法避免这样做。我想更改
typecast
块的绑定/范围
class Person
  include Typecast
  def age=(new_age)
    typecast do
      self.new_age :integer    # Avoids ambiguity because we used an
    end                        # explicit receiver.
  end
end

Person.new.age = 10
# => :integer
# => 10