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!

1

There are 1 answers

7
DigitalRoss On

I like your poetry mode code but it has led you into trouble here.

One way to kinda keep it in poetry mode but fix your operator priority issue is to do this:

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

Update: if you work in Big Corporation With Coding Standards you will need to make it a bit more boring. I thought this was obvious but the gallery is correctly noting the usual solution:

   @@robots.include?(name) ? reset : name