该问题与摩尔斯电码有关:
# 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 返回完全相同的输出?
我创建它的方式,我认为会有间距差异。