Iggy Iggy - 4 months ago 23
Ruby Question

ruby single word pig latin with regex

Calling forth ruby regex masters!

I am trying to solve this problem in ruby using regex. The input will be a single word. Two conditions apply:


  • If it starts with vowels [aeiou], it returns the word + 'way'. For example,
    pig_latin('aye') #=> 'ayeway'

  • If it starts with consonants, it moves the first letter of the word to the end of string, then + 'ay'.
    pig_latin('map') #=> 'apmay'



I have tried:

def pig_latin(ay)
ay.gsub(/\A[aeiou](w+)/, '\2\1way')
end

pig_latin('map') #=> 'map'
pig_latin('aye') #=> 'aye'


When I tried

ay.gsub(/^[aeiou](\w+)*/, '\2\1way')
pig_latin('map') #=> 'map'
pig_latin('aye') #=> 'yeway'


Getting close. At least it recognizes consonants - but it removes 'a' in 'aye'.

I have tried reading regex doc, especially on gsub and rubular helps to illuminate a bit, but I am still in the dark ages.

Answer

In case two gsub calls are allowed:

def pig_latin(ay)
    ay[0] =~ /[aeiou]/ ? ay.gsub(/([aeiou])(\w+)*/, '\1\2way') : ay.gsub(/([^aeiou])(\w+)*/, '\2\1ay')
end

pig_latin("aye") #=> ayeway
pig_latin("map") #=> apmay

In case two gsub calls are not allowed:

def pig_latin(ay)
    ay += ( (ay[0] =~ /[aeiou]/).nil? ? "" : "w")
    ay.gsub(/([^aeiou]?)([aeiou])(\w+)(.?)/, '\2\3\1\4ay')
end

pig_latin("aye") #=> ayeway
pig_latin("map") #=> apmay
Comments