Probably, to make a more general question is how to do list comprehension in Ruby.
Let's say given a number N (say N=5) I want to get an array like this:
[[0, 1], [0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
Using imperative way I can do:
arr = []
N = 5
(0..N-1).each do |i|
(i+1..N-1).each do |j|
arr << [i, j]
end
end
puts arr
Using functional way:
(0..N-1).collect{|el1| (el1+1..N-1).collect{|el2| [el1, el2]}}.flatten.each_slice(2).to_a
I don't like that the second example relies on the fact that the array is sorted in the right order. Is there a cleaner way to get the array in a functional way (without the extra flatten and slice)?