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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Wally W. (Guest)
on 2017-03-21 15:24
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 method `chomp' for nil:NilClass
(NoMethodError)


Thanks
Ronald F. (Guest)
on 2017-03-22 15:36
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.
Robert H. (Guest)
on 2017-03-22 19: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'
      break
    else
      puts 'Invalid input'
    end
  }
This topic is locked and can not be replied to.