From: Daniel Martin Date: 2007-04-27T21:21:05+09:00 Subject: Re: Ruby gotcha? [].all? always returns true "Dan Stevens (IAmAI)" writes: > if not my_arr.all? { |i| i.is_a(Integer) } > # Do stuff > end > > I expecting it to 'do stuff', however I found it was not. I discovered > that 'my_arr' was empty, which was not a surprise, but what did > surprise me was that all? called on an empty array appears to always > return true. > > I don't know about you, but these seems counter-intuitive to me. Does > anyone agree or disagree? It seems perfectly intuitive to me. There's a local law that states that all dogs must wear leashes when not confined behind a fence. We are in full compliance with that law, even though our front yard has no fence and we own no leashes - this is because we have no dogs. > I've now resorted to any? instead, like as follows: > > if not my_arr.any? { |i| not i.is_a(Integer) } > # Do stuff > end > > As far as it seems [].any? always returns false. The code should also > be slightly more efficient as it doesn't always have to check every > item of the array, not that I expect it to get very big. Actually, all? has the same efficiency characteristics. That is, the instant it finds something false, it returns false. -- s=%q( Daniel Martin -- martin@snowplow.org puts "s=%q(#{s})",s.to_a[1] ) puts "s=%q(#{s})",s.to_a[1]