【问题标题】:Convert string through hash通过哈希转换字符串
【发布时间】:2016-05-20 02:08:14
【问题描述】:

我正在尝试将一串摩尔斯电码转换为单词。我将字符串拆分为单词。然后我将每个单词拆分成一个由字母和数字组成的二级数组。

 def self.decode(str)
    decoded = ""
    arr = []
    p arr = str.split('  ')
    p arr.map! { |i| i.split('  ') }

    arr.each do |r|
      r.each do |i|
          decoded += @morse.invert[i].to_s[-1]
      end
    end

    p decoded
end

在我的hash 中,我使用数字。它们以N 开头。在to_s[-1]中,-1是去掉N

我收到此错误:

`+': no implicit conversion of nil into String

我可以弄清楚如何通过它,因为我没有在数组中看到 nil 值。

class Morse

    @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: '--..',
        ' ': ' ' ,
        N1: '.----',
        N2: '..---',
        N3: '...--',
        N4: '....-',
        N5: '.....',
        N6: '-....',
        N7: '--...',
        N8: '---..',
        N9: '----.',
        N0: '-----'
    }

def self.encode(str)
    encoded = ""
    sym_temp = ""
    str = str.upcase!
    str.each_char do |c|
        ascii_check = c.ord
        if ascii_check.between?(65,90)
            temp = str[c].to_sym
            encoded += "#{@morse[temp]}" + " "
        elsif ascii_check.between?(48,57)   
            temp = "N".concat(str[c]).to_sym
            encoded += "#{@morse[temp]}" + " "
        elsif ascii_check ===(32)
            temp = str[c].to_sym
            encoded += "#{@morse[temp]}"
        end
    end
    p encoded
end

def self.decode(str)
    decoded = ""
    arr = []
    # str.split('  ').map do |i|
    p arr = str.split('  ')
    p arr.map! { |i| i.split('  ') }

    arr.each do |r|
      r.each do |i|
        p  decoded += @morse.invert[i].to_s[-1].to_s
      end
    end             

    p decoded
end

# def self.read_file
    # # @Temp = File.read("preamble_encode.txt").chomp
      # # File.open('hiscore.txt'){|f| f.lines.map{|l| l.chomp!.split(',')}}
    # # @Temp = File.foreach("preamble_encode.txt", 'r') {|f| f.lines.map{|l| l.chomp}}

# end

# def self.write_file
    # # Temp2 = File.open('preamble_decode.txt', 'w') do |f|
        # # f.puts Temp2
    # # end
# end

end


test = "Abc 1oL!"
test2 = ".-- .  - .... .  .--. . --- .--. .-.. ."
Morse.encode(test)
Morse.decode(test2)

【问题讨论】:

  • 做一件事来快速追踪它。修改添加逻辑如下:decoded += @morse.invert[i].to_s[-1].to_s

标签: arrays ruby string


【解决方案1】:

你的问题在这里:

        :P => :'.--.',

哈希火箭右侧的冒号将其设为符号,而不是字符串。碰巧的是,您的解码测试用例包含一个 P。当您尝试查找 String '.--.' 时,它找不到它并返回 nil。

【讨论】:

  • 好眼睛! :) 通过使用较新的散列键/值表示法(在本例中为 P: '.--.')可能可以避免这种错字。双冒号会很显眼,很容易被发现。
  • 谢谢,我现在也更新了我的代码,它似乎仍然没有把任何东西解码,但至少它没有给我那个错误!
【解决方案2】:

您的问题已经得到解答,我想建议您如何编写编码和解码方法。

首先,散列的键应该是字符串而不是符号,因为散列用于编码由单字符串组成的字符串。我们还需要数字是'0''9',而不是'N0''N9'。空格由等于七个点的时间延迟表示,而不是点和破折号的组合,所以我用字符串'<delay>' 表示空格。请参阅Morse Wiki

由于哈希不会改变,我将其设为常量而不是实例变量的值。

CharactersToMorse = {
  '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' => '--..' , ' ' => '<delay>', '0' => '-----', '1' => '.----',
  '2' => '..---', '3' => '...--', '4' => '....-', '5' => '.....', '6' => '-....',
  '7' => '--...', '8' => '---..', '9' => '----.'
}

我们需要解码,所以我也将反向散列分配给一个常量。

MorseToCharacters = CharactersToMorse.invert
  #=> {".-"=>"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", "<delay>"=>" ", "-----"=>"0", ".----"=>"1", "..---"=>"2",
  #    "...--"=>"3", "....-"=>"4", "....."=>"5", "-...."=>"6", "--..."=>"7",
  #    "---.."=>"8", "----."=>"9"} 

我们的编码和解码方法现在非常简单。

def code(text)
  text.each_char.map { |c| CharactersToMorse[c] }
end

def decode(morse)
  morse.map { |m| MorseToCharacters[m] }.join(' ')
end

让我们试试吧。

text = "NOW IS THE TIME FOR 47 RUBIESTS TO COME TO THE AID OF THEIR BOWLING TEAM"

morse = code(text)
  #=> ["-.", "---", ".--", "<delay>", "..", "...", "<delay>", "-", "....",
  #    ".", "<delay>", "-", "..", "--", ".", "<delay>", "..-.", "---", ".-.",
  #    "<delay>", "....-", "--...", "<delay>", ".-.", "..-", "-...", "..",
  #    ".", "...", "-", "...", "<delay>", "-", "---", "<delay>", "-.-.", "---",
  #    "--", ".", "<delay>", "-", "---", "<delay>", "-", "....", ".", "<delay>",
  #    ".-", "..", "-..", "<delay>", "---", "..-.", "<delay>", "-", "....",
  #    ".", "..", ".-.", "<delay>", "-...", "---", ".--", ".-..", "..", "-.",
  #    "--.", "<delay>", "-", ".", ".-", "--"] 

decode(morse)
  #=> "NOW IS THE TIME FOR 47 RUBIESTS TO COME TO THE AID OF THEIR BOWLING TEAM"

如果由于某种原因CharactersToMorse 的键必须是符号,请将方法更改为:

def code(text)
  text.each_char.map { |c| CharactersToMorse[c.to_sym] }
end

def decode(morse)
  morse.map { |m| MorseToCharacters[m].to_s }.join(' ')
end

【讨论】:

  • 这样看会让它看起来很简单,我希望我可以使用字符串......但这是一个它们必须是符号的赋值。但这实际上真的很高兴看到,如果再次出现这种情况,我会记住这一点!
  • 如果键是符号,这是一个小改动。我在答案的末尾添加了解释。
  • 由于我不相信 1: 或 1=> 有效,因此如何使数字起作用仍然存在一些小困惑?
  • @Alex :'1' 是一个有效的符号。在哈希中,您可以使用 {:'1' =&gt; '·−−−−'}{'1': '·−−−−'}(需要 Ruby 2.2 或更高版本)
  • 谢谢,@Stefan。我已经回滚了。 :-)
猜你喜欢
  • 2015-03-20
  • 1970-01-01
  • 2016-10-21
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
  • 2015-08-21
  • 1970-01-01
相关资源
最近更新 更多