2011-05-02 63 views
0
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返回此錯誤是因爲它知道new_age是在方法參數中定義的局部變量。所以,當我改變Person類這樣的:可變範圍干擾Ruby中的DSL

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

紅寶石現在返回預期:integer

我的問題是,我該如何阻止局部變量干擾instance_eval塊?

回答

0

當你有一個變量和一個名稱相同的方法都存在於同一個範圍內時,消除歧義的方法是澄清接收者。在這種情況下,您希望接收器是self

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 
+0

是的,我知道這一點。我想知道是否有辦法避免這樣做。我想改變'typecast'塊的綁定/範圍 – RyanScottLewis 2011-05-02 10:57:16