Forum: Ruby Why i got this error in my code ?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
16f25494bb665defa3561c4cc21034c4?d=identicon&s=25 Wally W. (wally)
on 2017-03-21 14:24
input = " "
until input == 'quit'
    puts "
(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'
            puts "Invalid input"

# => output

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

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

# why this error?

..\Playground\:9:in `<main>': undefined method `chomp' for nil:NilClass

3a81ced4012650ca2004c9bff7b18202?d=identicon&s=25 Ronald F. (rovf)
on 2017-03-22 14:36
Did you read the definition of 'gets', for instance here?

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.
7e17d370dc95b48cd82944a62f1caf76?d=identicon&s=25 Robert H. (shevegen)
on 2017-03-22 18:43
> # why this error?
> ..\Playground\:9:in `<main>': undefined method `chomp' 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'
      puts 'Invalid input'
This topic is locked and can not be replied to.