From: Robert Klemme Date: 2005-07-13T22:20:51+09:00 Subject: Re: correct use of join? 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