Pig-latin sentence

I am trying to create a method that will take a string sentence as an argument, and translate that sentence into pig latin. I am currently trying to do this within a single method.

I can easily do this for one word:

def pig_latin_word(word)
  vowels = %w(a e i o u)
  word_array = word.split('')
  if vowels.include?(word_array[0])
    word_array.join('')
  else
    until vowels.include?(word_array[0])
      word_array += word_array.shift(1)
    end
    word = word_array.join('')
    "#{word}ay"
  end
end

      

Now I would like to do the same, but the method has to accept the offer. This is what I have so far:

def pig_latin_sentence(sentence)
  vowels = %w(a e i o u)
  sentence_array  = sentence.split.each_slice(1).map{|a| a.join('')}
  sentence_array.each do |word|
    if vowels.include?(word[0])
      sentence_array.join(' ')
    else
      until vowels.include?(word[0])
        word_array = word.split('')
        word_array += word_array.shift(1)
      end
      p sentence_array.join('ay ')
    end
  end
end

      

At first, I tried to take a sentence and slice it so that each word is split. I could then iterate over the array, with each word being an element. However, in order for me to execute the method .shift

, I would have to split each element of the string again. How can I achieve this?

Also, does anyone have a cleaner way of spelling one word?

+3


source to share


2 answers


As Dave Newton says, let your pig_latin_word process the words. If something goes wrong with the words, you will know where to look; similar to suggestions.

sentence.split.each_slice(1).map{|a| a.join('')}

      



is a code from someone who has worked too hard.

def pig_latin_sentence(sentence)
  pig_words = sentence.split.map do |word|
    pig_latin_word(word)
  end
  pig_words.join(" ")
end

      

+2


source


Here is the solution I made for the latin pig, it's a little shorter!



def pig_latin_ified(word)
  index = /[aeiou]/ =~ word
  return word if index == 0
  word_array = word.chars
  final_solution = (word_array + word_array.shift(index) + ["a", "y"]).join("")
end

      

0


source







All Articles