1

質問はモールス信号に関連しています:

# Build a function, `morse_encode(str)` that takes in a string (no
# numbers or punctuation) and outputs the morse code for it. See
# http://en.wikipedia.org/wiki/Morse_code. Put two spaces between
# words and one space between letters.
#
# You'll have to type in morse code: I'd use a hash to map letters to
# codes. Don't worry about numbers.
#
# I wrote a helper method `morse_encode_word(word)` that handled a
# single word.
#
# Difficulty: 2/5

describe "#morse_encode" do
  it "should do a simple letter" do
    morse_encode("q").should == "--.-"
  end

  it "should handle a small word" do
    morse_encode("cat").should == "-.-. .- -"
  end

  it "should handle a phrase" do
    morse_encode("cat in hat").should == "-.-. .- -  .. -.  .... .- -"
  end
end

私の解決策は

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

def morse_encode(str)
  arrayer = str.split(" ")
  combiner = arrayer.map {|word| morse_encode_word(word) }
  combiner.join("  ")
end

def morse_encode_word(word)
    letters = word.split("")

  array = letters.map {|x| MORSE_CODE[x]}

  array.join(" ")
end

morse_encode("cat in hat")
morse_encode_word("cat in hat")

morse_encode と morse_encode_word がまったく同じ出力を返すのはなぜですか?

私が作成した方法では、間隔の違いがあると思います。

4

2 に答える 2

6

フレーズを に渡すmorse_encode_wordと、文字で分割されます (つまり、 に't i'なり['t', ' ', 'i']ます。次に、この配列を['-', nil, '..'](because ) にマップしますMORSE_CODE[' '] == nil)。

そして、スペースで結合します'-' + ' ' + '' + ' ' + '..'(なぜならnil.to_s == '')。したがって、内部に 2 つのスペースを含む文字列が得られます'- ..'

于 2013-05-29T17:50:24.260 に答える
2

morse_encode_word を実行すると、スペースが取り除かれません...したがって、単語は分割されますが、スペースは保持されます。

morse_encode では、(分割のために) スペースを取り除きますが、結合を行うときにスペースを追加します。つまり、morse_encode_word と同じになります。

あなたが望むのは、morse_encode_word に余分なスペースがないことだと思います。x を morse_encode_word にマップする前に、x がスペースでないことを確認してください。

reject を使用してみてください:

def morse_encode_word(word)
  letters = word.split("")

  array = letters.reject{|x| x == " "}.map{|x| MORSE_CODE[x]}

  array.join(" ")
end
于 2013-05-29T18:02:36.477 に答える