1
votes

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.

2
you need to do it only with 1 gsub call? - Harsh Trivedi
Do you need to use regex? - Carl Markham
@CarlMarkham technically I don't. But I have solved something similar without regex. I wanted to challenge myself and limit myself to use as much regex as/if possible. But any solution is always welcome! I can always learn something from other people :) - Iggy

2 Answers

1
votes

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
1
votes

If you do not need to use regex you could do the following

pig_latin 'aye'

def pig_latin word
  if word[0].in? ['a', 'e', 'i', 'o', 'u']
    return word << 'way'
  else
    first = word.strip[0] # Get the first letter
    word = word.sub first, '' # remove the first letter from word
    return word << first << 'ay'
  end
end