我在調用本身的一個方法(遞歸循環),我會很感激一些單詞,方法或更正的代碼來解決這個問題。(另一個)堆棧級別太深紅寶石
代碼:
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!
用'ssn'方法內的'@ ssn'替換'ssn'。除非像'first_name'那樣創建'accessor'方法,否則不能使用'@'來訪問實例變量。 – tihom