Skip to content

Instantly share code, notes, and snippets.

@paulghaddad
Created February 23, 2015 13:22
Show Gist options
  • Save paulghaddad/664a5a69f7779440c550 to your computer and use it in GitHub Desktop.
Save paulghaddad/664a5a69f7779440c550 to your computer and use it in GitHub Desktop.
Exercism Ruby - Robot Name

Robot Name

Write a program that manages robot factory settings.

When robots come off the factory floor, they have no name.

The first time you boot them up, a random name is generated, such as RX837 or BC811.

Every once in a while we need to reset a robot to its factory settings, which means that their name gets wiped. The next time you ask, it gets a new name.

For bonus points

Did you get the tests passing and the code clean? If you want to, these are some additional things you could try:

  • Random names means a risk of collisions. Make sure the same name is never used twice. Feel free to introduce additional tests.

Then please share your thoughts in a comment on the submission. Did this experiment make the code better? Worse? Did you learn anything from it?

Source

A debugging session with Paul Blackwell at gSchool. view source

class Robot
attr_accessor :name
CHARACTERS = ('A'..'Z').to_a
DIGITS = ('0'..'9').to_a
def initialize
@name = generate_name
end
def reset
@name = generate_name
end
private
def generate_name
"#{random_letter_sequence(2)}#{random_number_sequence(3)}"
end
def random_letter_sequence(number_of_characters)
number_of_characters.times.inject('') { |string, iteration| string << CHARACTERS.sample }
end
def random_number_sequence(number_of_digits)
number_of_digits.times.inject('') { |string, iteration| string << DIGITS.sample }
end
end
require 'minitest/autorun'
require_relative 'robot'
class RobotTest < MiniTest::Unit::TestCase
def test_has_name
# rubocop:disable Lint/AmbiguousRegexpLiteral
assert_match /^[A-Z]{2}\d{3}$/, Robot.new.name
# rubocop:enable Lint/AmbiguousRegexpLiteral
end
def test_name_sticks
robot = Robot.new
robot.name
assert_equal robot.name, robot.name
end
def test_different_robots_have_different_names
# rubocop:disable Lint/UselessComparison
assert Robot.new.name != Robot.new.name
# rubocop:enable Lint/UselessComparison
end
def test_reset_name
robot = Robot.new
name = robot.name
robot.reset
name2 = robot.name
assert name != name2
# rubocop:disable Lint/AmbiguousRegexpLiteral
assert_match /^[A-Z]{2}\d{3}$/, name2
# rubocop:enable Lint/AmbiguousRegexpLiteral
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment