From: Rich Morin Date: 2007-05-25T19:13:41+09:00 Subject: Replacement idiom for "list_or_nil.to_a"? 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 Morin http://www.cfcl.com/rdm/resume rdm@cfcl.com http://www.cfcl.com/rdm/weblog +1 650-873-7841 Technical editing and writing, programming, and web development