Robert Klemme
5/29/2007 7:45:00 AM
On 25.05.2007 18:23, Rich Morin wrote:
> 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.
This is an issue only if foo is a method that does a complex calculation.
>> 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| ... }
This might create another object which might impose a performance hit.
>> 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...
There will likely be a performance hit if foo is something different
than an array because then it will have to be converted to an array.
Kind regards
robert