Reputation: 464
I have the arrays a = [-1,-2,-3,-4]
and b = [-1,-2,-3,4]
How can I make sure that a
contains only negative integers?
I can check that some of elements are negative a.select(&:negative?) == true
and b.select(&:negative?) == true
But I need to know that b.select(&:negative?).only == true
Upvotes: 4
Views: 5901
Reputation: 110685
You could simply consider the largest value:
arr = [-1,-2,-3,-4]
arr.empty? ? false : arr.max < 0
#=> true
if the array contains only integers. If the array may contain elements that are not integers, one must first confirm that only integers are present.
arr = [-1,-2,-3,-4, "cat", { a:1 }]
return false unless arr.all? { |e| e.is_a?(Fixnum) }
#=> false returned
Upvotes: 6
Reputation: 52357
You can use Enumerable#all?
here:
[-1,-2,-3,-4].all?(&:negative?)
#=> true
Btw, I think you are confused with what is happening here:
a.select(&:negative?) == true
This is not checking whether all elements are negative. What it is in fact is comparing resulting array of negative numbers with false
:
[-1,-2,-3,-4] == false
Of course, it will always return false
, because only false
is equal to false
.
Upvotes: 16