Last active
May 10, 2021 11:31
-
-
Save nofxx/3f3c35a32950b502eacb to your computer and use it in GitHub Desktop.
Morse Code in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class String | |
MORSE_CODE = { | |
a: '.-', b: '-...', c: '-.-.', d: '-..', e: '.', f: '..-.', | |
g: '--.', h: '....', i: '..', j: '.---', k: '-.-', l: '.-..', | |
m: '--', n: '-.', o: '---', p: '.--.', q: '--.-', r: '.-.', s: '...', | |
t: '-', u: '..-', v: '...-', w: '.--', x: '-..-', y: '-.--', z: '--..' | |
} | |
def to_morse_code | |
self.downcase.each_char.map { |c| MORSE_CODE[c.to_sym] }.join | |
end | |
alias_method :to_morse, :to_morse_code | |
end | |
"hello".to_morse | |
class MorseCode | |
attr_reader :text, :code | |
CODE = { a: '.-', b: '-...', c: '-.-.', d: '-..', e: '.', f: '..-.', | |
g: '--.', h: '....', i: '..', j: '.---', k: '-.-', l: '.-..', | |
m: '--', n: '-.', o: '---', p: '.--.', q: '--.-', r: '.-.', | |
s: '...', t: '-', u: '..-', v: '...-', w: '.--', x: '-..-', | |
y: '-.--', z: '--..' | |
} | |
def initialize(text) | |
fail "Nothing to say?" unless text | |
@text = text.downcase | |
parse_code | |
end | |
def parse_code | |
@code = text.each_char.map { |c| CODE[c] }.join | |
end | |
end | |
MorseCode.new("hello").code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment