Question

I'm calling a method within itself (recursive loop) and I'd appreciate some words, methods or corrected code to fix this.

Code:

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 output:

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!
Was it helpful?

Solution

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

The code above should work. You simply needed the @ symbol for the ssn inside of your method. Otherwise, it is clear that the recursive call is happening when you try to string-interpolate your ssn. Note, that instance variables are only visible with the @. It is not implicit. Clearly, you would run into issues similar to what you ran into.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top