Luis F. Vidal Luis F. Vidal - 1 year ago 71
Ruby Question

Basic Pig Latin | Troubles with .each

I'm solving a basic training exercise and I got stuck. I have to Move the first letter of each word to the end of it, then add 'ay' to the end of the word.. I've been googling and came up with this code:

def pig_it translate_pig_latin
move_letters = text.split(' ')
.each do {|x| x[1..-1] << x.[0] << 'ay' }
move_letters.join(' ')

But for some reason it gives me this error

-e:4: syntax error, unexpected '|', expecting '}'
.each do {|x| x[1..-1] << x.[0] << 'ay' }

I know it's a problem with the
method, but after reading the documentation and googling around I can't figure out what's wrong with it.

Answer Source
def translate_pig_latin(text)
     move_letters = text.split(' ')
         .each { |x| return x[1..-1] << x[0] << 'ay' }
     move_letters.join(' ')     

Some notes -

  • As another user stated, don't mix and match do/end and {}
  • Also, when using bracket notation to retrieve an item from an array, don't use a . like you have in x.[0]
  • Your .each block is doing the correct thing(when you adhere to the above note) but isn't returning the result (by which I am confused). If you add an explicit return then your code works as above

A more drawn out method if this helps you understand what's happening better

    def translate_pig_latin(text)
        # create array to contain piglatinified phrase
        new_phrase = []
        # each word of the original phrase do
        text.split(' ').each do |x|
            # grab the characters after the first character
            new_word = x[1..-1]
            # add the first character plus 'ay' to the end of the string
            new_word << x[0] + 'ay'
            # add the newly piglatinified string to the phrase
            new_phrase << new_word
        # turn the phrase into a space separated string
        new_phrase.join(' ') 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download