Ruby中可变作用域对DSL的干扰
Ruby返回此错误,因为它知道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)
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