Jason Rodriguez
Jason Rodriguez

Reputation: 153

Can you append to specific elements in an array based on if statement conditions?

I am a developer bootcamp student and was having an issue with one of my projects. We are using Ruby to code a Pig Latin page. I got it passing tests up until the point where it needs to accept multiple words:

def pig_latina(word)
  # univeral variables
vowels = ['a','e','i','o','u']
user_output = ""
  # adds 'way' if the word starts with a vowel
  if vowels.include?(word[0]) 
     user_output = word + 'way'     
  # moves the first consonants at the beginning of a word before a vowel to the end  
  else 
    word.split("").each_with_index do |letter, index|

      if vowels.include?(letter)
        user_output = word[index..-1] + word[0..index-1] + 'ay'
      break
      end
    end 
  end   
  # takes words that start with 'qu' and moves it to the back of the bus and adds 'ay'
  if word[0,2] == 'qu'
  user_output = word[2..-1] + 'quay'
  end
  # takes words that contain 'qu' and moves it to the back of the bus and adds 'ay'
  if word[1,2] == 'qu'
  user_output = word[3..-1] + word[0] + 'quay'
  end
  # prints result
  user_output
end

I don't know how to do it. This isn't homework or anything. I tried

  words = phrase.split(" ")
    words.each do |word|
    if vowels.include?(word[0])
      word + 'way'

but I think that the else statement is messing it all up. Any insight would be greatly appreciated! Thanks!!

Upvotes: 0

Views: 176

Answers (2)

tigeravatar
tigeravatar

Reputation: 26640

def pig_latina(word)
  prefix = word[0, %w(a e i o u).map{|vowel| "#{word}aeiou".index(vowel)}.min]
  prefix = 'qu' if word[0, 2] == 'qu'
  prefix.length == 0 ? "#{word}way" : "#{word[prefix.length..-1]}#{prefix}ay"
end

phrase = "The dog jumped over the quail"
translated = phrase.scan(/\w+/).map{|word| pig_latina(word)}.join(" ").capitalize

puts translated  # => "Ethay ogday umpedjay overway ethay ailquay"

Upvotes: 1

Cole Pilegard
Cole Pilegard

Reputation: 582

I would separate your logic into two different methods, one method for converting a single word (sort of like you have), and another method for taking a sentence, splitting up the words, and calling your former method on each one. It might look like this:

def pig(words)
  phrase = words.split(" ")
  phrase.map{|word| pig_latina(word)}.join(" ")
end

Upvotes: 1

Related Questions