Skip to content

Instantly share code, notes, and snippets.

@nofxx
Last active May 10, 2021 11:31
Show Gist options
  • Save nofxx/3f3c35a32950b502eacb to your computer and use it in GitHub Desktop.
Save nofxx/3f3c35a32950b502eacb to your computer and use it in GitHub Desktop.
Morse Code in ruby
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