Home > Software design >  How to use 2 for loop in Ruby on rails?
How to use 2 for loop in Ruby on rails?

Time:08-11

I am learning ruby on rails and i am trying to iterate my data from 2 loops. But didn't know how it can be possible.

Here is my array in controller:

@players = [1, 2, 3]

        for(@i; @i < @players; @i  )
            for(@j = @i 1; @j < @players; @j  )
                puts @i "with" @j
            end
        end

I want [1,2], [1,3], [2,3] as a result

CodePudding user response:

To get all combinations of size 2 (1st and 2nd, 1st and 3rd, 2nd and 3rd) can use Array#combination. With a block, it will yield each pair:

@players = [1, 2, 3]

@players.combination(2) do |i, j|
  puts "#{i} with #{j}"
end

Output:

1 with 2
1 with 3
2 with 3

Without a block, combination returns an Enumerator:

@players.combination(2)
#=> #<Enumerator: ...>

To get an array of combinations, call its to_a method:

@players.combination(2).to_a
#=> [[1, 2], [1, 3], [2, 3]]

CodePudding user response:

You use each to loop

You should read https://www.tutorialspoint.com/ruby/ruby_overview.htm#

@players.each do |player|
   p player
end
  • Related