Iggy Iggy - 3 months ago 8
Ruby Question

How to display an array with ruby nested each?

Given a list of array, I want to display all pair combination of the array in the form of array of two. For example, let's say I have an array of

[1,2,3]
.

[1, 1]
[1, 2]
[1, 3]
[2, 1]
[2, 2]
[2, 3]
[3, 1]
[3, 2]
[3, 3]


Expected result

This is the function I came up with:

def all_combination(list)
list.each do |i|
list.each do |j|
puts [i,j]
end
end
end

arr1 = [1,2,3] #arr1 can be an array of any size. It will always be integer.
all_combination(arr1)


However, when I do the above code, it displays

1
1
1
2
1
3
...


It seems like there is a gap in my fundamental ruby knowledge. Why
puts [i,j]
does not work? How can I make it display an actual array like it shows on Expected result section?

I can make it work with
puts "#{i}, #{j}"
, but it does not return an array pair
[a,b]

pjs pjs
Answer

There's a builtin method for what you want:

[1,2,3].permutation(2).each {|a| p a}

If you prefer to stick with your own method (to get "pairs" of items with themselves), change puts [i,j] to either p [i,j] or to puts [i,j].to_sputs works with strings.

Comments