Unexpected repeating in 'while true' loop

Hi all,

I'm writing a program that I hope will function as way to track what
books I own, what books I want, and what books I have lent out and to
whom. My 'library_client.rb' file was working as expected as far as the
'while true' loop is concerned, until I added:

library = Library.new(:lib_data => ARGV[0])

Now, when I run the following command in terminal:

ruby library_client.rb lib_data

I get 11 iterations of my 'nav_options' hash and the program crashes
with a

`<main>': undefined method `chomp' for nil:NilClass (NoMethodError)

I really don't understand why adding

library = Library.new(:lib_data => ARGV[0])

would cause my program to repeat and crash. I've included all my source
code. Thoughts?

Attachments:
http://www.ruby-forum.com/attachment/9045/library.rb
http://www.ruby-forum.com/attachment/9046/library_client.rb
http://www.ruby-forum.com/attachment/9047/lib_data

···

--
Posted via http://www.ruby-forum.com/.

If you check the documentation of Kernel#gets:

you will see that by default it reads from files present in ARGV. When
you call your script passing lib_data as a parameter, gets will read
line by line of that file, instead of the standard input. As that file
has 11 lines, you get 11 iterations through the while loop. In order
to force reading from the standard input you could use:

    nav_choice = $stdin.gets.chomp

Also, your else case doesn't print anything, maybe you are missing a
"puts" there (line 48)?

Jesus.

···

On Wed, Dec 11, 2013 at 12:45 PM, Mike Vezzani <lists@ruby-forum.com> wrote:

Hi all,

I'm writing a program that I hope will function as way to track what
books I own, what books I want, and what books I have lent out and to
whom. My 'library_client.rb' file was working as expected as far as the
'while true' loop is concerned, until I added:

library = Library.new(:lib_data => ARGV[0])

Now, when I run the following command in terminal:

ruby library_client.rb lib_data

I get 11 iterations of my 'nav_options' hash and the program crashes
with a

`<main>': undefined method `chomp' for nil:NilClass (NoMethodError)

I really don't understand why adding

library = Library.new(:lib_data => ARGV[0])

would cause my program to repeat and crash. I've included all my source
code. Thoughts?

Attachments:
http://www.ruby-forum.com/attachment/9045/library.rb
http://www.ruby-forum.com/attachment/9046/library_client.rb
http://www.ruby-forum.com/attachment/9047/lib_data

--
Posted via http://www.ruby-forum.com/\.

Jesus,

Wow! Many thanks for the super prompt reply! Also, thank you for both
explaining the behavior of the bug in my program as well as providing me
documentation to reference and a suggested solution. The suggested fix
worked great! I'm now off to read more about Kernel#gets.

~Mike

···

--
Posted via http://www.ruby-forum.com/.