Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check that every element in an array is greater than the one before it?

I'm using Ruby 2.4. I have an array of strings, which are themselves numbers. So something like

["1", "2", "3", "5"]

How do I check that the integer version of every element in the array (except the first) is greater than the one before it? So for instance the function performed on the above would return true, but an array like

["1", "5", "4", "6"]

would return false (because "4" is not greater than "5".


1 Answers

An alternative way to phrase your predicate is: "For all consecutive pairs of numbers, is it true that the second is greater than the first"? This can be almost directly expressed in code:

ary.map(&:to_i).each_cons(2).all? {|first, second| second > first }

By the way: this property is called "strict monotonicity".

like image 96
Jörg W Mittag Avatar answered Feb 05 '26 20:02

Jörg W Mittag



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!