2014-09-13 26 views
3

以下Ruby代碼引發了最後顯示的混淆錯誤「no id given」。我如何避免這個問題?在method_missing中修復「no id given」消息

def method_missing(a,*b) 
    a = 17 
    super 
end 

foobar #=> `method_missing': no id given (ArgumentError) 

當你的第一個參數的值更改爲除符號以外的東西后調用supermethod_missing這個錯誤出現了:

class Asset; end 

class Proxy < Asset 
    def initialize(asset) 
    @asset 
    end 
    def method_missing(property,*args) 
    property = property.to_s 
    property.sub!(/=$/,'') if property.end_with?('=') 
    if @asset.respond_to?(property) 
     # irrelevant code here 
    else 
     super 
    end 
    end 
end 

Proxy.new(42).foobar 
#=> /Users/phrogz/test.rb:13:in `method_missing': no id given (ArgumentError) 
#=> from /Users/phrogz/test.rb:13:in `method_missing' 
#=> from /Users/phrogz/test.rb:19:in `<main>' 

回答

3

這個問題的核心可以用這個簡單的測試顯示。修復?不要這樣做。例如,從原來的問題的方法可以被改寫爲:

def method_missing(property,*args) 
    name = property.to_s 
    name.sub!(/=$/,'') if name.end_with?('=') 
    if @asset.respond_to?(name) 
    # irrelevant code here 
    else 
    super 
    end 
end 

另外,一定要明確地傳遞一個符號作爲第一個參數super

def method_missing(property,*args) 
    property = property.to_s 
    # ... 
    if @asset.respond_to?(property) 
    # ... 
    else 
    super(property.to_sym, *args) 
    end 
end 
+0

如果更改參數,但只是將它更改爲符號,它也會起作用 - 您不必在調用「super」時明確地傳遞它。 (例如在你的例子中將'a = 17'改爲'a =:「17」'將會導致'undefined method'17'...')。 – matt 2014-09-14 10:35:07

+1

誤導'沒有給出id(ArgumentError)'錯誤信息已被更改爲'沒有給出符號「https://github.com/ruby/ruby/pull/1013 – 2017-04-20 12:39:19