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.
Bd6d879843b3ec697543002fe1780682?d=identicon&s=25 Wally Wally (wally)
on 2017-03-21 14: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
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2017-03-22 14: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.
4828d528e2e46f7c8160c336eb332836?d=identicon&s=25 Robert Heiler (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'
      break
    else
      puts 'Invalid input'
    end
  }
This topic is locked and can not be replied to.