Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Translates Morse code from a mobile phone style keypad into plain English

// Translates Morse code specially input from a Nokia 3510i or Nokia 6600 to plain English. I primarily used the button 1 for a dot, 2 for a dash and 5 for the terminator. I later extended the flexibility of the inputs by allowing 4 to be a dot, 7 a dash and 9 as the terminator. eg. ghi = dots pqrs = dashes wxyz = terminators and spaces.

#!/usr/bin/ruby
#filename: morsecode.rb

require 'net/http'
require 'rexml/document'

include REXML

class Morsecode
  def initialize
    @doc_mlookup = load_lookup('http://jamesrobertson.eu/p/xml/', 'morsecode.xml')
    @doc_charmcode = load_lookup('http://jamesrobertson.eu/p/xml/', 'charmcode.xml')
  end

  def load_lookup(url, filename)
    xml_data = Net::HTTP.get_response(URI.parse(url + filename)).body
    Document.new(xml_data)
  end

  def decode_string(doc, a_buffer)
    pstring = ''
    a_buffer.each do |word|
      pstring += doc.root.elements["code[@encode='" + word + "']"].text
    end
    pstring
  end

  def decode_kstring(buffer)
    decode_string(@doc_charmcode, buffer.scan(/./))
  end

  def decode_mstring(buffer)
    decode_string(@doc_mlookup, buffer.split('4'))
  end

  def decode(buffer)
    decode_mstring(decode_kstring(buffer)) if buffer.length > 0
  end
end

#test
a = Morsecode.new
puts a.decode('gwpwrwgw')


« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS