D
Dan Stevens (IAmAI)
Something in caught me out today. I wanted to test that the contents
of the array where all instances of particular class, and if not, do
stuff. The example isn't exactly what my code did, but it illustrates
my point:
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?
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.
of the array where all instances of particular class, and if not, do
stuff. The example isn't exactly what my code did, but it illustrates
my point:
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?
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.