Module: Telegraph

Includes:
MorseCharacters
Defined in:
lib/telegraph.rb

Overview

Telegraph module provides a simple text-to-morse, morse-to-text translator.

It uses as reference the document <t>RECOMMENDATION ITU-R M.1677</t> from the International Telecommunication Union, Radiocommunication Sector (ITU-R), the United Nations agency for information and communication technology issues.

Defined Under Namespace

Classes: MorseTransmission

Constant Summary

Constants included from MorseCharacters

MorseCharacters::DASH, MorseCharacters::DOT, MorseCharacters::End_of_work, MorseCharacters::Error, MorseCharacters::ITU_Morse, MorseCharacters::International_extensions, MorseCharacters::Invitation_to_transmit, MorseCharacters::LETTERS_TO_MORSE, MorseCharacters::MORSE_TO_LETTERS, MorseCharacters::Space_between_words, MorseCharacters::Starting_signal, MorseCharacters::Understood, MorseCharacters::Wait

Class Method Summary collapse

Class Method Details

.morse_to_text(morse) ⇒ Object

Transforms a string of morse code into a string of text decoding using the RECOMMENDATION ITU-R M.1677.

It expects the character ‘.’ as the short signal, the character ‘-’ as the long signal, a space as separation between letters and seven spaces as separation between words.

The returned string is completly downcased.

Telegraph.morse_to_text(".... . .-.. .-.. ---        .-- --- .-. .-.. -..")  #=> hello world"


36
37
38
39
40
# File 'lib/telegraph.rb', line 36

def self.morse_to_text(morse)
  morse.split(LETTERS_TO_MORSE[" "]).inject([]){|words, morse_word|
    words << morse_word.split(" ").inject(""){|word, morse_char| word + MORSE_TO_LETTERS[morse_char]}
  }.join(" ")
end

.text_to_morse(text) ⇒ Object

Transforms a string of plain text into a string of morse code using the character ‘.’ as the short signal and the character ‘-’ as the long signal. The encode is made following the official RECOMMENDATION ITU-R M.1677. The returned string uses a single space as letter separator and a seven spaces gap as word separator.

Telegraph.text_to_morse("Hello world")  #=> ".... . .-.. .-.. ---        .-- --- .-. .-.. -.."


21
22
23
24
25
# File 'lib/telegraph.rb', line 21

def self.text_to_morse(text)
  text.strip.downcase.split(" ").inject([]){|morse_words, word| 
    morse_words << word.chars.inject(""){|morse_word, character| [morse_word, LETTERS_TO_MORSE[character]].join(" ").strip}
  }.join(LETTERS_TO_MORSE[" "]).strip
end