-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 回答