Home > front end >  How can I do a ruby method that converts morse code into numbers?
How can I do a ruby method that converts morse code into numbers?

Time:12-07

I made this ruby method to convert numbers to morse code and it works, but now I'm trying to do the reverse (convert a morse code input into numbers), and I can't figure out how.

def convert(morse_code)
    morse_code = {
      "1" => ".----",
      "2" => "..---",
      "3" => "...--",
      "4" => "....-",
      "5" => ".....",
      "6" => "-....",
      "7" => "--...",
      "8" => "---..",
      "9" => "----.",
      "0" => "-----"
     }
    @converted = gets.chomp().downcase.gsub(/\w/, morse_code)
  end

puts convert(@converted)

I tried to change the places of the strings in the hash but it actually won't work.

What I've tried so far:

def convert(morse_code)     
  morse_code = {         
    '.----': '1', '..---': '2',         
    '...--': '3', '....-': '4',         
    '.....': '5', '-....': '6',         
    '--...': '7', '---..': '8',         
    '----.': '9', '-----': '0'      
  }     
  @converted = gets.chomp().gsub(/\w/, morse_code)   
end  

puts convert(@converted) 

CodePudding user response:

You're redefining the parameter morse_code with your hash, so your param is useless. use => to have strings as key in hash, like { 'key' => 'value' }

At the end, it looks better like this:

MORSE_CODE_TO_NUMBERS = {         
  '.----' => 1, '..---' => 2,         
  '...--' => 3, '....-' => 4,         
  '.....' => 5, '-....' => 6,         
  '--...' => 7, '---..' => 8,         
  '----.' => 9, '-----' => 0      
}     

def convert_numbers_to_morse
  puts 'Enter your morse phrase:'
  msg = gets

  word_array = msg.split
  word_array_converted = word_array.map{|code| MORSE_CODE_TO_NUMBERS[code]}

  word_array_converted.join(' ')
end

puts convert_numbers_to_morse
  •  Tags:  
  • ruby
  • Related