[Ruby] Reduce
Posted: Wed Feb 14, 2018 6:50 am
I had to look at an array and get either true or false, depending on any value being greater than 1 or lower than -1.
After some time I came up with this:
I think it is the shortest form to get the desired result (but please post even shorter versions!), probably even in high execution speed.
'reduce' is a method of the array class that tries to reduce the array to one value, using a provided block. That block gets populated with a memo and the current value, and you can initialize memo (here: reduce(false) sets memo to false). If you don't, it will be initialized with the first value of the array - not good if you're looking for true or false.
The rest of the code checks if the absolute value is greater or equal 1 (digital clipping occured) and sets memo to true. If not, memo is passed back unaltered.
It would be an improvement if, with similar short code, one could break out of the loop on the first occurence of the condition. So, if you know a trick for that, please share
After some time I came up with this:
- Code: Select all
over = a.reduce(false) { |memo, n| n.abs >= 1 ? memo = true : memo }
I think it is the shortest form to get the desired result (but please post even shorter versions!), probably even in high execution speed.
'reduce' is a method of the array class that tries to reduce the array to one value, using a provided block. That block gets populated with a memo and the current value, and you can initialize memo (here: reduce(false) sets memo to false). If you don't, it will be initialized with the first value of the array - not good if you're looking for true or false.
The rest of the code checks if the absolute value is greater or equal 1 (digital clipping occured) and sets memo to true. If not, memo is passed back unaltered.
It would be an improvement if, with similar short code, one could break out of the loop on the first occurence of the condition. So, if you know a trick for that, please share