Natalia Natalia - 4 years ago 91
Ruby Question

In Ruby, how do I calculate how close an element is to its neighbor?

I'm using Ruby 2.4. I have an array of strings, which are in fact numbers ...

["1", "2", "3", "7", "8", "9"]


How do I write an expression that will tell me the percentage of elements in the array (neglecting the last one) that have an absolute value difference of 1 with the element that follows it? So in the above, this is true for four out of the five elements, (since "7" has a difference of four following the "3" element), so I would expect the expression to return .8.

Answer Source
arr = ["1", "2", "3", "7", "8", "9"].map(&:to_i)
result  = arr.each_cons(2).count { |a, b| (a - b).abs == 1 }
percentage = result / (arr.count - 1).to_f
 #=> 0.8
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download