find pairs with distance in ruby array -


i have big array sequence of values. check if values in place x have influence on values on place x+distance want find pairs

pair = [values[x], values[x+1]] 

the following code works

pairs_with_distance = [] values.each_cons(1+distance) |sequence|    pairs_with_distance << [sequence[0], sequence[-1]] end 

but looks complicated , wonder if if make shorter , clearer

you can make code shorter using map directly:

pairs_with_distance = values.each_cons(1 + distance).map { |seq|    [seq.first, seq.last] } 

i prefer example below, because has short, readable lines of code, , because separates steps -- approach allows give meaningful names intermediate calculations (groups in case). can come better names based on real domain of application.

values   = [11,22,33,44,55,66,77] distance = 2  groups = values.each_cons(1 + distance) pairs  = groups.map { |seq| [seq.first, seq.last] }  p pairs 

Comments