JaTo
JaTo

Reputation: 2832

Why are my Ruby methods returning the same thing?

The question is related to 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

My solution is

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")

Why are morse_encode and morse_encode_word returning the exact same output?

The way I created it, I would think there would be spacing differences.

Upvotes: 1

Views: 201

Answers (2)

mikdiet
mikdiet

Reputation: 10018

When you pass a phrase into morse_encode_word, it splits it by letters (that is, 't i' becomes ['t', ' ', 'i']. Next, you map this array to ['-', nil, '..'] (because MORSE_CODE[' '] == nil).

And then you join it with space, '-' + ' ' + '' + ' ' + '..' (because nil.to_s == ''). So you get string with two spaces inside, '- ..'.

Upvotes: 6

dev
dev

Reputation: 1507

When you do morse_encode_word you are not getting rid of spaces... So it will split your words, but keep the space.

In morse_encode you get rid of the space (because of split), but you add it back in when you do the join. So it ends up being the same as morse_encode_word.

I would guess that what you want is no extra spaces in morse_encode_word. Just do a check to make sure x is not a space before you map it in morse_encode_word.

Try to use reject:

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

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

  array.join(" ")
end

Upvotes: 2

Related Questions