2

I'm working on a pig latin program on Ruby and was having some trouble. The console shows this error

expected: "appleay"
got: ["appleay"]
def translate(str)

alphabet = ("a".."z").to_a
vowels = ["a","e","i","o","u"]
consonants = alphabet - vowels

str.split.map do |word|
    if vowels.include?(word[0])
        word.to_str + "ay"

    elsif word[0..2].include?("qu")
        if word[0..1] == "qu"
            (word[2..-1] + "quay").join(" ")
        else
            word[3..-1] + word[0] + "quay"
        end
    elsif consonants.include?(word[0]) && consonants.include?(word[1]) && consonants.include?(word[2].to_s)
        word[3..-1] + word[0..2] + "ay"
    elsif consonants.include?(word[0]) && consonants.include?(word[1]) 
        word[2..-1] + word[0..1] + "ay"
    elsif cononants.include?(word[0])
        word[1..-1] + word[0] + "ay"

    else 
        word
    end
end
end

Thanks in advance!

2 Answers 2

1

This is because you are using map. If you read the docs you can find:

Returns a new array with the results of running block once for every element in enum.

Since the return type is an Array, you are getting Array as result and not a String (which here happens to be the first element of the Array.)

A simple solution will be always to return the first element of the Array. You can achieve this by:

str.split.map do |word|
    if vowels.include?(word[0])
      ....
    else
      word
    end
end.first # returning the first element of resultant array, nil if none present
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help :)
0

You are using Array#map. This method returns an array. Since it is the last statement of your method translate, this array will implicitly returned. Thus, when you call the method it shall output an array. To fix this, do

str.split.map do |word|
    if vowels.include?(word[0])
        #...
    elsif word[0..2].include?("qu")
        #...
    end
end.join(' ')

This join(' ') will join each element into one string, each element separated by a single space (' '). This makes the output of the method a string instead of an array, fixing your problem while accounting for an array that is more than one element in size, unlike the other answer by shivam, which will only return the first element. It is more scalable this way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.