From: "Aníbal" Date: 2007-05-30T19:15:15+09:00 Subject: Re: Replacement idiom for "list_or_nil.to_a"? list_or_nil.each do |value| unless list_or_nil.nil? -- An�bal Rojas http://www.rubycorner.com http://www.hasmanydvelopers.com On May 25, 6:13 am, Rich Morin wrote: > Many scripting languages, including Ruby, will "do nothing > gracefully" when asked to iterate through an empty list. > That is, they iterate NO times. > > However, many Ruby methods do not return empty lists when > nothing is found. Instead, they return nil. This means > that idioms such as: > > list_or_nil.each do |value| > ... > end > > will fail. As a workaround, I've been using this idiom: > > list_or_nil.to_a.each do |value| > ... > end > > However, I gather that this will soon be deprecated: > > http://www.megasolutions.net/ruby/to_a-68350.aspx > > This page suggests putting the list in brackets: > > [list_or_nil] > > but this doesn't solve MY problem: > > >> list_or_nil=nil > => nil > >> [list_or_nil] > => [nil] > > because the loop will now run once with the value nil. > I really dislike having to wrap the iteration block in > an "if" block: > > if list_or_nil > list_or_nil.each do |value| > ... > end > end > > and this is only marginally better: > > list_or_nil.each do |value| > ... > end if list_or_nil > > I suppose I could define my own to_a method for nil, > but that seems a bit questionable, as well. So, is > there a Better Way To Do It? > > -r > --http://www.cfcl.com/rdm Rich Morinhttp://www.cfcl.com/rdm/resume r...@cfcl.comhttp://www.cfcl.com/rdm/weblog +1 650-873-7841 > > Technical editing and writing, programming, and web development