Ruby Quiz <james / grayproductions.net> wrote: > This week's quiz is to write a program that displays LCD style numbers at > adjustable sizes. Here's my solution: **************************** [begin code ] **************************** #!/usr/local/bin/ruby -w require 'getoptlong' # --------------------------------------------------------------------- class Digit @@chars = [ " ", "-", "|" ] @@segments = [ [ [0,1,0], [2,0,2], [0,0,0], [2,0,2], [0,1,0] ], # 0 [ [0,0,0], [0,0,2], [0,0,0], [0,0,2], [0,0,0] ], # 1 [ [0,1,0], [0,0,2], [0,1,0], [2,0,0], [0,1,0] ], # 2 [ [0,1,0], [0,0,2], [0,1,0], [0,0,2], [0,1,0] ], # 3 [ [0,0,0], [2,0,2], [0,1,0], [0,0,2], [0,0,0] ], # 4 [ [0,1,0], [2,0,0], [0,1,0], [0,0,2], [0,1,0] ], # 5 [ [0,1,0], [2,0,0], [0,1,0], [2,0,2], [0,1,0] ], # 6 [ [0,1,0], [0,0,2], [0,0,0], [0,0,2], [0,0,0] ], # 7 [ [0,1,0], [2,0,2], [0,1,0], [2,0,2], [0,1,0] ], # 8 [ [0,1,0], [2,0,2], [0,1,0], [0,0,2], [0,1,0] ] # 9 ] attr_reader :height def initialize( num, size ) @matrix = @@segments[ num ] @height = @matrix.size self.scale_to_size( size ) if size > 1 end def scale_to_size( size ) t = size - 1 @matrix.each { |l| t.times { l.insert(-2, 0) } } @matrix.each { |l| l.fill(1, l.index(1),size) if l.include?(1) } t.times { @matrix.insert( 1, @matrix[1]) } t.times { @matrix.insert(-2, @matrix[-2]) } @height = @matrix.size end def display_line( line ) @matrix[ line ].each { |c| print @@chars[c] } print " " end end # --------------------------------------------------------------------- class LCD def initialize( num, size=1 ) @digits = Array.new num.each_byte { |b| @digits << Digit.new( b.to_i - 48, size ) } end def display for line in 0... / digits.first.height @digits.each { |d| d.display_line( line ) } puts end end end # --------------------------------------------------------------------- def print_usage( message=nil ) puts "Usage: lcd [-s size] digits" end # --------------------------------------------------------------------- print_usage & exit if ARGV.empty? size = 2 opts = GetoptLong.new( ["--size", "-s", GetoptLong::REQUIRED_ARGUMENT] ) opts.each { |opt, val| size = val.to_i if opt == "--size" } print_usage & exit if ARGV.empty? digits = ARGV[0].gsub( /[^0-9]/, "" ) lcd = LCD.new( digits, size ) lcd.display # --------------------------------------------------------------------- **************************** [end code ] ****************************** -- Luc Heinrich - lucsky / mac.com