Ruby map function for "pig latin"

Marc Fletcher

I am attempting to write a ruby function that takes in a string of words and turns it into Pig Latin. I am breaking the string into an array, and attempting to iterate over each element. When "eat pie" is put in, the result is "eat ie", but I am unsure why.

string = "eat pie"    
array = string.split(" ")

array.map do |word| 

 if word[0].chr == "a" || word[0].chr == "e" || word[0].chr == "i" || word[0].chr == "o" || word[0].chr == "u"

   word = word + "ay"

 elsif word[1].chr == "a" || word[1].chr == "i" || word[1].chr == "o" || word[1].chr == "u"
  temp = word[0]
  word[0] = ""
  word = word + temp
  word = word + "ay"

elsif word[2].chr == "a" || word[2].chr == "i" || word[2].chr == "o" || word[2].chr == "u"
  temp = word[0] + word[1]
  word[0] = ""
  word[0] = ""
  word = word + temp 
  word = word + "ay"

else ## three consonants
  temp = word[0] + word[1] + word[2]
  word[0] = ""
  word[0] = ""
  word[0] = ""
  word = word + temp 
  word = word + "ay"

 end ## end of if statement

end ## end of iteration 

puts array.join(" ")
Jamie Pirie

Agree with the other answers supplied, here's a slightly less verbose version of your code in case it helps you.

input = 'pig latin is awesome'

arr = input.split(' ').map do |wrd|
    if %w(a e i o u).include? wrd[0]
      wrd + 'ay'
    elsif %w(a i o u).include? wrd[1]
      wrd[1..-1] + wrd[0] + 'ay'
    elsif %w(a i o u).include? wrd[2]
      wrd[2..-1] + wrd[0] + wrd[1] + 'ay'
    else
      wrd[3..-1] + wrd[0] + wrd[1] + wrd[2] + 'ay'
    end
end.join(' ')

puts arr

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related