-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!
4

1 に答える 1

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。インスタンス変数は、@. 暗黙的ではありません。明らかに、遭遇したものと同様の問題に遭遇するでしょう。

于 2013-11-04T09:34:29.227 に答える