2013-11-04 43 views
-2

我在調用本身的一個方法(遞歸循環),我會很感激一些單詞,方法或更正的代碼來解決這個問題。(另一個)堆棧級別太深紅寶石

代碼:

class Person_verifier 
    def initialize(first_name, ssn) 
    @first_name = first_name 
    @ssn = ssn.to_s 
    end 
    def first_name 
    @first_name 
    end 
    def ssn 
    if ssn[9] =~ /[1, 3, 5, 7, 9]/ 
     "#{first_name}'s social security number is #{ssn} and based on the second-last number, #{first_name} is a Male" 
    elsif ssn[9] =~ /[0, 2, 4, 6, 8]/ 
     "#{first_name}'s social security number is #{ssn} and based on the second-last number, #{first_name} is a Female" 
    else 
     return false 
    end 
    end 
end 

IRB輸出:

load './ssn.rb' 
d = Person_verifier.new("MyName", "010285-123X") 
d.first_name 
# => "MyName" 
d.ssn 
# => SystemStackError: stack level too deep 
    from /home/username/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/irb/workspace.rb:86 
    Maybe IRB bug! 
+0

用'ssn'方法內的'@ ssn'替換'ssn'。除非像'first_name'那樣創建'accessor'方法,否則不能使用'@'來訪問實例變量。 – tihom

回答

0
def ssn 
    if @ssn[9] =~ /[1, 3, 5, 7, 9]/ 
    "#{first_name}'s social security number is #{@ssn} and based on the second-last number, #{first_name} is a Male" 
    elsif @ssn[9] =~ /[0, 2, 4, 6, 8]/ 
    "#{first_name}'s social security number is #{@ssn} and based on the second-last number, #{first_name} is a Female" 
    else 
    return false 
    end 
end 

上面的代碼應該工作。您只需在方法內部使用@符號作爲ssn。否則,很顯然,遞歸調用正在發生,當您嘗試對您的ssn進行字符串插值時。請注意,該實例變量僅在@中可見。這不是隱含的。顯然,你會遇到類似於你遇到的問題。

+0

添加@無助於此。我犯了同樣的錯誤。是的,我確實保存並重新加載了文件。想法? – user2951911

+0

你在'ssn [9]'中加入了@和'在字符串中插入了'ssn'嗎?我只是測試它,當我使用'@'時,代碼適用於我。 – David

+1

啊,沒有注意到@內的字符串。非常感謝你,我對這個愚蠢的問題表示歉意。 – user2951911