Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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

like image 874
Kirill Zhuravlov Avatar asked Oct 15 '25 01:10

Kirill Zhuravlov


1 Answers

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.

like image 146
Andrey Deineko Avatar answered Oct 17 '25 17:10

Andrey Deineko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!