为什么我的Ruby方法返回相同的东西?

时间:2013-05-29 17:41:05

标签: ruby

问题与Morse code

有关
# 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会返回完全相同的输出?

我创造它的方式,我认为会有间距差异。

2 个答案:

答案 0 :(得分:6)

当您将短语传递到morse_encode_word时,它会按字母分隔(即't i'变为['t', ' ', 'i']。接下来,您将此数组映射到['-', nil, '..'](因为MORSE_CODE[' '] == nil)。

然后你加入空间'-' + ' ' + '' + ' ' + '..'(因为nil.to_s == '')。所以你得到两个空格的字符串,'- ..'

答案 1 :(得分:2)

当你做morse_encode_word时,你没有摆脱空间......所以它会分裂你的话语,但保留空间。

在morse_encode中,你摆脱了空间(因为分裂),但是当你进行连接时你将它重新添加。所以它最终与morse_encode_word相同。

我猜你想要的是morse_encode_word中没有额外的空格。在morse_encode_word中映射之前,只需进行检查以确保x不是空格。

尝试使用拒绝:

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

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

  array.join(" ")
end