Created
April 5, 2010 21:56
-
-
Save timanglade/356951 to your computer and use it in GitHub Desktop.
A Morse decoder/encoder
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
# Morse Decoder / Encoder | |
# | |
# Originally from http://refactormycode.com/codes/513-morse-code-encoder-decoder | |
# With modifications. | |
# Uploaded & shared for the purpose of a class at UMLV. | |
module Morse | |
$LETTER = Hash[*%w/ | |
A .- N -. | |
B -... O --- | |
C -.-. P .--. | |
D -.. Q --.- | |
E . R .-. | |
F ..-. S ... | |
G --. T - | |
H .... U ..- | |
I .. V ...- | |
J .--- W .-- | |
K -.- X -..- | |
L .-.. Y -.-- | |
M -- Z --.. | |
/] | |
$CODE = $LETTER.invert | |
def self.encode(message) | |
encoded_message = [] | |
words = message.split(" ") | |
words.each do |word| | |
encoded_word = "" | |
word.split(//).each do |letter| | |
if $LETTER.has_key?(letter.upcase) | |
encoded_word << $LETTER[letter.upcase] | |
encoded_word << " " | |
end | |
end | |
encoded_message << encoded_word | |
end | |
return encoded_message.join("| ") | |
end | |
def self.decode(message) | |
decoded_message = "" | |
words = message.split("|") | |
words.each do |word| | |
word.split(/\s/).each do |letter| | |
if $CODE.has_key?(letter) | |
decoded_message << $CODE[letter] | |
end | |
end | |
decoded_message << " " | |
end | |
decoded_message | |
end | |
def self.encode_file(f) | |
File.open(f).each do |line| | |
encode(line) | |
end | |
end | |
def self.decode_file(f) | |
File.open(f).each do |line| | |
decode(line) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment