Skip to content

Instantly share code, notes, and snippets.

@ArtemBorodinEvgenyevich
Created November 21, 2021 21:40
Show Gist options
  • Select an option

  • Save ArtemBorodinEvgenyevich/1e1a804255f1ac9c3def1f361e62675e to your computer and use it in GitHub Desktop.

Select an option

Save ArtemBorodinEvgenyevich/1e1a804255f1ac9c3def1f361e62675e to your computer and use it in GitHub Desktop.
Ruby digits to LCD task
# frozen_string_literal: true
# enhanced improvement for basic string class :)
class String
def i?
!!(self =~ /^\d+$/)
end
end
# LCD class for converting integers into LCD-like digits
class LCD
def initialize
create_patterns
create_digits
end
# create hash of patterns use to build LCD digits
def create_patterns
@patterns = {
0 => ' ',
1 => ' _ ',
2 => '| |',
3 => '|_|',
4 => '|_ ',
5 => ' _|',
6 => '| ',
7 => ' |'
}
end
private :create_patterns
# map each digit to patterns it uses respectively
def create_digits
@patterns = {
0 => [@patterns[1], @patterns[2], @patterns[3]],
1 => [@patterns[0], @patterns[7], @patterns[7]],
2 => [@patterns[1], @patterns[5], @patterns[4]],
3 => [@patterns[1], @patterns[5], @patterns[5]],
4 => [@patterns[0], @patterns[3], @patterns[7]],
5 => [@patterns[1], @patterns[4], @patterns[5]],
6 => [@patterns[1], @patterns[4], @patterns[3]],
7 => [@patterns[1], @patterns[7], @patterns[7]],
8 => [@patterns[1], @patterns[3], @patterns[3]],
9 => [@patterns[1], @patterns[3], @patterns[5]]
}
end
private :create_digits
def display(numbers)
raise 'Expecting argument to be a positive integer' unless numbers.i?
digits = numbers.chars.map(&:to_i)
(0..2).each do |row|
line = ''
digits.each do |digit|
line += @patterns[digit][row]
line += ' ' if digit != digits.last
end
puts line
end
end
end
if __FILE__ == $PROGRAM_NAME && (ARGV[0])
begin
LCD.new.display(ARGV[0])
rescue StandardError => e
puts "#{e.class}: #{e.message}"
end
else
puts 'Type a positive integer to convert into LCD digit. (Like: 123456789)'
end
# frozen_string_literal: true
require 'test/unit'
# enhanced improvement for basic string class :)
class String
def i?
!!(self =~ /^\d+$/)
end
end
# test case for string class
class TestString < Test::Unit::TestCase
def setup
@str_i = '1234'
@str_neg = '-1345'
@str_c = '(2+3i)'
end
def test_str_i
assert_true(@str_i.i?)
end
def test_str_neg
assert_false(@str_neg.i?)
end
def test_str_c
assert_false(@str_c.i?)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment