Iggy Iggy - 1 year ago 55
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, 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]

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

However, when I do the above code, it displays


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

pjs pjs
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download