0

I'm doing a 'morse code' exercise and running into some difficulty. I'll skip posting the hash I created that stores the code and the letter.

The morse code in the method call has 3 spaces between the 'words' Example -

decodeMorse('.... . -.--   .--- ..- -.. .')

My strategy was to split the words first using split(/\s\s\s/) which gives me separate arrays for each word, but then those arrays need a split(' ') to get to the letters.

This is my code -

  sc = str.split(/\s\s\s/)
    sc.each do |string|
      string.split(' ').map {|key| morsecode[key]; }

It works okay, but I'm left with two arrays at the end:

=> ["h", "e", "y"]
=> ["j", "u", "d", "e"]

Normally, if I had two or more arrays that had assigned variable names I would know how to concat them but what I've tried and searched on hasn't changed the situation. Obviously all I get from join('') is the two words together with no space between them.

1
  • 1
    What is your question? Commented Jul 26, 2017 at 1:45

2 Answers 2

1

There is no need to convert the string to an array, then convert the elements of the array to arrays, join the latter arrays then join the former array. Instead one can simply use the form of String#gsub that employs a hash to make substitutions.

morsecode = {  ".-"=>"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",  "   "=>" ",    " "=>""}

Notice the last two key-value pairs in morsecode.

'.... . -.--   .--- ..- -.. .'.gsub(/[.-]+|   | /, morsecode)
  #=> "hey jude"

The regular expression reads, "match one or more dits and dahs or three spaces or one space". Note that three spaces must precede the single space in the regex.

Sign up to request clarification or add additional context in comments.

Comments

0
  sc = str.split(/\s\s\s/)

  deciphered = sc.map do |string|
    string.split(' ').map {|key| morsecode[key]; }.join
  end

  deciphered.join(' ')

2 Comments

Well it looked promising but right now I'm getting an "undefined method 'join' for nil:Nilclass
update it is working! @m. simon borg I just had to removed the deciphered.join after the end Works great, much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.