From: Robert Klemme Date: 2007-05-25T21:00:09+09:00 Subject: Re: Replacement idiom for "list_or_nil.to_a"? On 25.05.2007 12:13, 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? Probably. How do you like list_or_nil and list_or_nil.each do |x| ... end Or irb(main):001:0> class NilClass irb(main):002:1> def each; self; end irb(main):003:1> include Enumerable irb(main):004:1> end => NilClass irb(main):005:0> nil.each {|x| puts x} => nil irb(main):006:0> ? Kind regards robert