Skip to content

Instantly share code, notes, and snippets.

@metallurgix
Last active August 29, 2015 14:04
Show Gist options
  • Save metallurgix/c575be2203f86b673676 to your computer and use it in GitHub Desktop.
Save metallurgix/c575be2203f86b673676 to your computer and use it in GitHub Desktop.
Morse Encoding and Decoding
class String
#Decodes Morse String
#A space is assumed to be represented by 2 spaces in encoded string
def decode_morse
result=Array.new
self.gsub!(" "," | ")
morse= {"|"=>" ",".-"=>"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",
".----"=>"1","..---"=>"2","...--"=>"3","....-"=>"4","....."=>"5","-...."=>"6","--..."=>"7","---.."=>"8","----."=>"9","-----"=>"0"}
self.split(" ").each do |chr|
if morse[chr]!=nil
result<<morse[chr]
else
result<<chr
end
end
return result.join("")
end
#Encodes a regular string
#A space char in the regular string is represented by 2 spaces after encoding
def encode_morse
result=Array.new
morse={"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"=>"--.."," "=>"|",
"1"=>".----","2"=>"..---","3"=>"...--","4"=>"....-","5"=>".....","6"=>"-....","7"=>"--...","8"=>"---..","9"=>"----.","0"=>"-----",}
self.split("").each do |chr|
if morse[chr]!=nil
result<<morse[chr]
else
result<<chr
end
end
result.join(" ").delete("|")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment