lundi 20 juin 2016

Why the program pass all tests if I use regular if statement in the method but says `stack level too deep` when using a ternary operator instead?

I was working on coding challenge called Robot name. I also had tests for that. The program passed all the tests. The code is below..

class Robot
  attr_accessor :name
  @@robots = []
  def initialize
    @name = self.random_name
    @@robots << self.name
  end

  def random_name
    name = ''
    2.times do
      name  << ('a'..'z').to_a.sample
    end
    3.times do
      name  << (1..9).to_a.sample.to_s
    end
    no_duplicate(name.upcase)
  end

  def reset
    @name = self.random_name
  end

  def no_duplicate(name)
    if @@robots.include? name
      reset
    else
      name
    end
  end
end

If you need to see the tests file you can look it up here robot_name_tests.

Then I started to refactor and one of the first things was to refactor no_duplicate method. So after refactoring the code looked like this

class Robot

  ...
  # the rest of code stayed the same

  def no_duplicate(name)
    @@robots.include? name ? reset : name
  end
end

With this version all tests showed SystemStackError: stack level too deep. Why does it give this error and what is going on behind the scenes in both cases considering the code provided? Thanks!

Aucun commentaire:

Enregistrer un commentaire