Created
July 19, 2013 22:47
-
-
Save TGOlson/6042906 to your computer and use it in GitHub Desktop.
Morse Code Generator
This file contains 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
# 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