I am attempting to learn Ruby by converting a Java program to Ruby, but I’ve been coming up with an error surrounding this block of code:
def create
@user_input = String.new()
# @word_arr = Array.new
print "Enter the text to be converted to pig latin, EOF to quit: "
while gets do
STDOUT.flush
@user_input = gets.chomp
@word_arr = @user_input.string.split(' ')
@word_arr.each { |x| puts x.engToLatin() + ' '}
print "EOF to Quit"
@user_input = ""
end
end
I’ve been getting this error:
EnglishToPigLatin.rb:14:in `create': private method `chomp' called for nil:NilClass (NoMethodError)
from EnglishToPigLatin.rb:60
This is the area around line 60:
#if __FILE__ == $0
mg = EnglishToPigLatin.new
mg.create
#end
Essentially what I am trying to do is while there is still input, get that input, split it up into individual words, and run each word through a Pig Latin conversion method.
It looks like you’re trying to get input inside of your loop.
Try
Otherwise you’re trying to get the next line of input when there isn’t one. Additionally,
doisn’t necessary for awhilestatement.You also don’t need to reset
@user_inputto''.And since this is all in a block, you don’t need to use instance variables, unless the methods you call need them.
Also your conditional is always true.
getswill block until it gets a line of input. You can useloopfor an infinite loop that ends on an interrupt.Also, you needn’t flush
STDOUTif you use aputsfor the last line there instead of aprint.The whole thing could be a script or a method in a module. An instance doesn’t even need to be made. And if you do, instead of using two lines with your
mg.create, you should define aninitializemethod. This is used as a constructor then, and whatever you set when you create an instance should be put there.It can all be done like this: