Skip to content

Instantly share code, notes, and snippets.

@photomattmills
Last active August 29, 2015 14:16
Show Gist options
  • Save photomattmills/20696ef01d563ed38912 to your computer and use it in GitHub Desktop.
Save photomattmills/20696ef01d563ed38912 to your computer and use it in GitHub Desktop.
morse translator
# BUCKET = ::AWS::S3::Bucket.new(AWS_CONFIG["medium_bucket"])
#
# derivatives = Derivative.where(label: 'high_res_proxy_mp4', upload_complete: nil)
#
# derivatives.inject([]) do |array, derivative|
# s3_file = BUCKET.objects[derivative.file_path] rescue nil
# if s3_file && s3_file.exists? && s3_file.content_length == derivative.file_size
# array << derivative
# end
# array
# end
# words = message.split(" ")
class MorseTranslator
def self.to_text(message)
self.new(message).text
end
def self.to_morse(message)
self.new(message).morse
end
def initialize(message)
@message = message
end
def text
words(@message).inject(""){|translated_text, word| translated_text + translate_word(word) + " " }.downcase
end
def morse
@message.split("").map(&:upcase).map{|character| table[character] }.join(" ")
end
def words(message)
message.split(" ")
end
def table
table = {
"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" => "--..",
"0" => "-----",
"1" => ".----",
"2" => "..---",
"3" => "...--",
"4" => "....-",
"5" => ".....",
"6" => "-....",
"7" => "--...",
"8" => "---..",
"9" => "----.",
" " => " "
}
table.default("")
table
end
def translate_word(word)
table.default = "*"
characters = word.split(" ")
characters.map{|c| table.invert[c] }.join("")
end
end
plain_message = "The sky above the port was the color of television, tuned to a dead channel."
morse_message = "- .... . ... -.- -.-- .- -... --- ...- . - .... . .--. --- .-. - .-- .- ... - .... . -.-. --- .-.. --- .-. --- ..-. - . .-.. . ...- .. ... .. --- -. - ..- -. . -.. - --- .- -.. . .- -.. -.-. .... .- -. -. . .-.. "
puts MorseTranslator.to_text(morse_message)
puts MorseTranslator.to_morse(plain_message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment