Kirill Zhuravlov Kirill Zhuravlov - 1 month ago 8
Ruby Question

Ruby: How to check that all elements in array are negative integers

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

Answer

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.