From: Rich Morin Date: 2007-05-26T01:23:59+09:00 Subject: Re: Replacement idiom for "list_or_nil.to_a"? Thanks for the suggestions! Here's a summary, with comments: > foo.to_a.each {|value| ... } This is what I was using. It's nice to know that it's not going away, after all. > foo.to_a.each {|value| ... } if foo This moves the "if" clause away from the iteration, which might make it harder to see. Also, it evaluates foo twice (could duplicate side-effects if foo is a method or be a performance issue id evaluating foo is expensive). > foo and foo.each {|value| ... } A bit wordy and obscure. Also, it evaluates foo twice. > class NilClass > def each; self; end > include Enumerable > end > > foo.each {|value| ... } This shortens the usage code, but I don't like playing with the definition of NilClass. Specifically, this might confuse a human reader or get in the way of code that already expects the current behavior. > (foo || []).each {|value| ... } This smells like line-noise, but is otherwise quite adequate. > (foo || VOID).each {|value| ... } > (foo || void).each {|value| ... } Aside from the line-noise issue, these seem similar to me. Both require the use of a supplementary definition, however, which the reader might have to loop up. > Array(foo).each {|value| ... } This seems like an improvement, from a clarity standpoint. My preference, at this point, is for either: > foo.to_a.each {|value| ... } > Array(foo).each {|value| ... } I think I prefer the latter, from a clarity standpoint. Also, the fact that to_a is being deprecated in other contexts might confuse some readers. If foo is a BIG array, there might be performance differences between these two, but I'm loathe to second-guess interpreter implementation issues of this sort... -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