From: Joseph Paish Date: 2005-07-13T22:31:36+09:00 Subject: Re: correct use of join? On July 13, 2005 07:20, Robert Klemme wrote: > Joseph Paish wrote: > > when i run a (large) script i am writing, this is the output i get on > > the screen (there are actually several hundred lines of output). > > note the "nil" on the first line. > > > > nil > > ["10/12/2001", "bought", "10000", "abc", "0.100", 0.2345, "17.43"] > > ["01/02/2005", "sold", "100", "widget2", "0.143", 0.4567, "22.45"] > > > > assuming that each line of the output is called single_record, when i > > type single_record.class, i find out that it is an Array. so far, so > > good. > > > > when i include the line > > > > puts single_record.join(" ") > > > > in the script in order to print single_record out as a > > space-separated string, i get the following message : > > > > my_command_prompt$ ruby ~/ruby_dir/program_name.rb > > nil > > /my_command_prompt/ruby_dir/program_name.rb:377: undefined method > > `join' for nil:NilClass (NoMethodError) > > from /my_command_prompt/ruby_dir/program_name.rb:239:in `each' > > from /my_command_prompt/ruby_dir/program_name.rb:239 > > > > when i use irb to do the example on the web page > > http://pine.fm/LearnToProgram/?Chapter=07, everything works perfectly. > > > > if single_record is in fact an array (and single_record.class tells > > me it is), what am i doing wrong? I have a feeling it has to do with > > the appearance of the word "nil" in the first line of output. > > Obviously the first time you access single_record it's nil. And nil > doesn't join. You can do several things: > > puts single_record && single_record.join(" ") > single_record and puts single_record.join(" ") > puts single_record.join(" ") if single_record > puts single_record.to_a.join(" ") > > and probably a lot more. But maybe it's just a bug that lead to the nil > and it normally cannot happen. > > Kind regards > > robert fantastic. i used this one since it is the clearest to me : puts single_record.join(" ") if single_record there is obviously a logic bug somewhere in the script, but getting it running without errors was the first step. thanks again joe