Basic Pig Latin Translator returning a NoMethodError

35 Views Asked by At

What I've got here gives me the solution I'm looking for but I get a NoMethodError for the slice method when I run it.

def pig_it(text)
  b4pig = text.split(" ")
  l1 = b4pig[0].slice(0,1)
  l2 = b4pig[1].slice(0,1)
  l3 = b4pig[2].slice(0,1)
  l4 = b4pig[3].slice(0,1)
  
  done = b4pig[0].delete(l1)+l1+"ay " + b4pig[1].delete(l2)+l2+"ay " + b4pig[2].delete(l3)+l3+"ay " + b4pig[3].delete(l4)+l4+"ay"
  return done
  
end

All the program needs to do is convert the first phrase to the second phrase

('Pig latin is cool'),'igPay atinlay siay oolcay') ('This is my string'),'hisTay siay ymay tringsay')

1

There are 1 best solutions below

0
Cary Swoveland On

I suggested one possible reason for the exception in a comment on the question, but you have not given enough information for readers to provide a definitive explanation.


I would like to suggest an alternative construction of your method that has three advantages:

  • the argument, a string, may contain any number of words;
  • punctuation is permitted; and
  • whitespace is preserved (e.g, tabs, line terminators, extra spaces)

The method is as follows.

def pig_it(text)
  text.gsub(/[a-z]+/i) { |word| format("%s%sya", word[1..], word[0] }
end

Let's try it.

pig_it "Baa, baa black sheep\nHave you any wool?"
  #=> "aaBya, aabya lackbya heepsya\naveHya ouyya nyaya oolwya?"

See String#gsub and Kernel#format.

/[a-z]+/i is a regular expression. [a-z] is a character class. It matches exactly one character in the character class. The character class contains all lower case letters of the alphabet. [a-z]+ matches one or more lower-case letters. The i following / means the expression is case insensitive, meaning the expression matches one or more letters, each letter being lower or upper case. It follows that whitespace and punctuation are not matched.

The block ({ |word| .... }) contains the block variable word which holds each match of the regular expression. In the example, word will in turn hold "Baa", "baa", "black" and so on.

Suppose word holds "black", then

word[0]   #=> "b"
word[1..] #=> "lack"

format("%s%sya", word[1..], word[0])
  #=> format("%s%sya", "lack", "b")
  #=> "lackbya"

I kept your method name because I do not think it can be improved upon.