Skip to content

Instantly share code, notes, and snippets.

@TGOlson
Created July 19, 2013 22:47
Show Gist options
  • Save TGOlson/6042906 to your computer and use it in GitHub Desktop.
Save TGOlson/6042906 to your computer and use it in GitHub Desktop.
Morse Code Generator
# Generates morse code based on input. Splits string and uses a morse code hash to convert letters.
# morse_encode("q").should == "--.-"
# morse_encode("cat").should == "-.-. .- -"
# morse_encode("CAT in hat").should == "-.-. .- - .. -. .... .- -"
def morse_encode(str)
string_split = str.downcase.split(' ')
coded_words = string_split.map {|wrd| morse_encode_word(wrd)}
coded_words.join(' ')
end
def morse_encode_word(word)
word_split = word.split('')
coded_letters = word_split.map {|let| morse_encode_letter(let)}
coded_letters.join(' ')
end
def morse_encode_letter(letter)
m_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" => "--.." }
m_code[letter]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment