Why i got this error in my code?


#1

input = " "
until input == ‘quit’
puts "
Menu
(1) Hi!
(2) Credits
(3 or quit) Exit"

input = gets.chomp.to_s

case input
    when "1" then
        puts "Hi!"
    when "2" then
        puts "Written By: wally"
    when "3" then
        input = 'quit'
    else
        puts "Invalid input"
end

end

=> output

Menu
(1) Hi!
(2) Credits
(3 or quit) Exit
Written By: wally

Menu
(1) Hi!
(2) Credits
(3 or quit) Exit

why this error?

…\Playground:9:in <main>': undefined methodchomp’ for nil:NilClass
(NoMethodError)

Thanks


#2

why this error?

…\Playground:9:in <main>': undefined methodchomp’ for nil:NilClass

I recommend to write code in such a way that you can handle nil objects.

Here is how I would rewrite it:

loop {
user_input = $stdin.gets.chomp
case user_input
when ‘1’
puts ‘Hi!’
when ‘2’
puts ‘Written By: wally’
when ‘3’
break
else
puts ‘Invalid input’
end
}


#3

Did you read the definition of ‘gets’, for instance here?

http://ruby-doc.org/core-2.4.0/IO.html#method-i-gets

It says:

Returns nil if called at end of file.

Hence, your ‘gets’ encounters an EOF. You should verify the value
returned from ‘gets’, before processing it further.