RamJet RamJet -4 years ago 53
Ruby Question

Create a new array based on a relationship between elements in an existing array in ruby

Let's say I have the following array,

a = [1, 2, 6, 10, 11]

and I want to return a new array, (b), containing the sum of adjacent elements that differ by one. In this case the returned array would be

b = [3, 21]

i.e. a[0] and a[1] differ by one, so sum them and add 3 to b.

a[3] and a[4] differ by one, so sum them and add 21 to b.

Answer Source

You can initialize a b variable and use each_cons, taking two consecutive elements from the array, then use map, inside you can get the sum of those two values per array if the substraction of both values is equal to 1, as you'll get nil values then you can compact the "mapped" result:

a = [1, 2, 6, 10, 11]
b = a.each_cons(2).map do |value|
  value.reduce(:+) if value[1] - value[0] == 1
# => [3, 21]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download