Python coding contest/Ruby
From 22C3
Ruby coders, unite!
Contents[hide] |
[edit]
seven_seg.rb
class String @@digits = ' _ | ||_| | | _ _||_ _ _| _| |_| | _ |_ _| _ |_ |_| _ | | _ |_||_| _ |_| _|'; def to_7seg create_line(0) + create_line(1) + create_line(2) end private def create_line number seg = '' scan(/./) { |ch| raise "Unknown character for LED: #{ch}" unless ch.match /\d/ seg += @@digits[ch.to_i*9, 9][number*3, 3] } seg + "\n" end end
[edit]
cleaned_up.rb
217 Bytes, but changed interface: ruby cleanup.rb 0123 321 178
def t a d=' _ | ||_| | | _ _||_ _ _| _| |_| | _ |_ _| _ |_ |_| _ | | _ |_||_| _ |_| _|' 0.upto(2){|n| s='' a.split(//).each{|c| s+=d[c.to_i*9,9][n*3,3] } puts s } end ARGV.each {|x| t(x) }
[edit]
test_vectors.rb
module TestVectors def TestVectors::each(&block) yield('23', " _ _ \n _| _|\n|_ _|\n") yield('123', " _ _ \n | _| _|\n | |_ _|\n") end end
[edit]
test.rb
require 'test/unit' require 'seven_seg' require 'test_vectors' class SevenSegmentTest < Test::Unit::TestCase def test_definition assert(String.new.respond_to?(:to_7seg)) end def test_format s = '0123456789' assert_kind_of(String, s) assert_kind_of(String, s.to_7seg) assert_equal("\n" * 3, "".to_7seg) assert_equal(3, s.to_7seg.count("\n")) end def test_invalid assert_raise(RuntimeError) { "ccc".to_7seg } assert_raise(RuntimeError) { "22c3".to_7seg } assert_raise(RuntimeError) { "22c".to_7seg } assert_raise(RuntimeError) { "c3".to_7seg } assert_raise(RuntimeError) { "c3d2".to_7seg } end def test_vectors TestVectors::each { |string,segment| assert_equal(string.to_7seg, segment) } end end