2015-09-26 284 views
-2

我只是玩弄w/Ruby並嘗試創建一個函數,但由於某種原因,它並不按照我認爲的方式工作。不知道爲什麼我有這個問題,但這裏是我的代碼:未定義的方法NoMethodError

class Script 
    print "Enter a number: " 
    number = gets 

    def random (temp) 
     puts "#{temp}" 
     puts "inside function" 
    end 

    random (number) 
end 

錯誤:

Script.rb:13:in `<class:Script>': undefined method `random' for Script:Class (NoMethodError) 
from Script.rb:1:in `<main>' 
+2

你認爲它會是什麼樣的方式?我運行它,沒有錯誤。 – songyy

+0

wtf ...太奇怪了。它仍然不工作,我複製粘貼我所有的代碼。 – halapgos1

+0

我其實很確定它不工作。現在再試一次。我懷疑它去實際的功能。 – halapgos1

回答

1

問題是,您將random方法定義爲實例方法,但在類級別上調用該方法。你有兩個選擇,以解決這個問題:

使它成爲一個類的方法(注意self):

class Script 
    def self.random(temp) 
    puts "#{temp}" 
    puts "inside function" 
    end 

    print "Enter a number: " 
    number = gets 

    random(number) 
end 

或改變方法,首先創建一個實例(注意new):

class Script 
    def random(temp) 
    puts "#{temp}" 
    puts "inside function" 
    end 

    print "Enter a number: " 
    number = gets 

    new.random(number) 
end 
+0

很酷,謝謝你的解釋!像魅力一樣工作。 :) – halapgos1

0

random是一個實例方法,而不是一個類的方法,使你的腳本提出NoMethodError,你應該創建一個Script類的對象,然後調用隨機方法。

class Script 
    print "Enter a number: " 
    number = gets 

    def random (temp) # it is a instance method. 
     puts "#{temp}" 
     puts "inside function" 
    end 

    Script.new.random(number) 
end 

或將random方法定義爲類方法。

class Script 
    print "Enter a number: " 
    number = gets 

    def self.random (temp) # define random as a class method 
     puts "#{temp}" 
     puts "inside function" 
    end 

    random(number) 
end 
相關問題