2016-09-26 93 views
-1

我是Ruby新手。我的一個練習是去除箭頭編程並引發異常。我不斷收到undefined method for validate_region_and_shapeRuby:獲取未定義的方法錯誤NoMethodError

def self.classify(region, shape) 
    # Alternative for raising exception within classify method 
    #raise Error_Message unless CLASSIFICATIONS.include? (region) 
    #raise Error_Message unless CLASSIFICATIONS[region].include? (shape) 
    if validate_region_and_shape(region, shape) 
    places = CLASSIFICATIONS[region][shape] 
    "You have a(n) '#{places}'" 
    end 
    end 

    def validate_region_and_shape(region, shape) 
     raise Error_Message if valid_region? 
     raise Error_Message if valid_shape? 
    end 

    def valid_region? 
    CLASSIFICATIONS.include?(region) 
    end 

    def valid_shape? 
    CLASSIFICATIONS[region].include?(shape) 
    end 

    end 

任何幫助將不勝感激。

+0

你的代碼不能編譯,你有一個太多的'end'。縮進使得它看起來像'def'在def self.classify'裏面。你也大幅改變了代碼,新代碼沒有你原來的問題。目前還不清楚你在問什麼。 – Schwern

+1

另外,應該'valid_region?'方法將'region'作爲一個arg,同樣'valid_shape'要''形狀'? – Rashmirathi

回答

1

你剛纔定義的時候有一個錯字validate_region_and_shape?

編輯:

如果您需要擺脫例外的,那麼你可以嘗試像

def validate_region_and_shape(region, shape) 
    CLASSIFICATIONS.include?(region) && CLASSIFICATIONS[region].include?(shape) 
end 

def classify(region, shape) 
    # Alternative for raising exception within classify method 
    #raise Error_Message unless CLASSIFICATIONS.include? (region) 
    #raise Error_Message unless CLASSIFICATIONS[region].include? (shape) 
    if validate_region_and_shape?(region, shape) 
    arrowhead = CLASSIFICATIONS[region][shape] 
    "You have a(n) '#{arrowhead}' arrowhead. Probably priceless." 
    else 
    raise Error_Message 
    end 
end 
+0

我試過了。他們建議何時調用一個方法?除了返回真或假以外,不應該做任何事情。它不應該引發例外。我試圖用單獨的方法進行驗證。 – Skipoura

+0

@YoussefKaib你在問什麼不是很清楚,你能詳細說明你正在做什麼嗎?我編輯了我的答案,是你想要做的事情。 – Rashmirathi

0

你已經有了一個這裏發生的事情很少。首先,你爲validate_region_and_shape方法使用了兩個不同的名稱。你用一個問號來調用它,但沒有定義它。所以,要麼改變這種:

if validate_region_and_shape?(r... 

到:

if validate_region_and_shape(r... 

或更改:

def validate_region_and_shape(r... 

到:

def validate_region_and_shape?(r... 

你也將其定義爲一個實例方法(沒有self),但從中調用它類方法。由於沒有實例,因此沒有使用該名稱的實例方法。所以,你需要使它像第一個類一樣......

def self.validate_region_and_shape(region, shape) 
    raise ... 
相關問題