Phone Numbers in Ruby

John Cleary (@TheRealBifter) is doing a nice project - The 12 TDD's of Xmas. Day 10 was the Phone number prefix problem. I did it in Ruby. Here's the code from traffic-light 14.

Tests first (very minimal - I'm a bit pressed for time):
require './consistent'
require 'test/unit'

class TestUntitled < Test::Unit::TestCase

  def test_consistent_phone_list
    list = { 
      'Bob' => '91125426',
      'Alice' => '97625992',
    }
    assert consistent(list)
  end

  def test_inconsistent_phone_list
    list = { 
      'Bob' => '91125426',
      'Alice' => '97625992',
      'Emergency' => '911'
    }
    assert !consistent(list)
  end

end
Code second:
def consistent(list)
  list.values.sort.each_cons(2).none? { |pair| prefix(*pair) }
end

def prefix(lhs,rhs)
  rhs.start_with? lhs
end
The each_cons from the previous problem proved very handy here. As did none? I really feel I'm starting to get the hang of ruby. You can replay my entire progression (warts and all) on Cyber-Dojo (naturally).

No comments:

Post a comment