Home>

I'm making a janken program with multiple people in Ruby.
As a function to be realized,
・ Janken with 3 or more players (up to 100 players).
・ The number of people can be decided freely. (Variable length)
・ Janken is performed 100 times with the number of people, and the result (why and how many wins or how many times it is divided) is output.
,
Therefore, the following error message occurred while implementing the second function.

Error message
janken.rb: 22: in `block (2 levels) in<main>': undefined method` []' for nil: NilClass (NoMethodError)
Applicable source code
puts "Start janken"
count_rock = 0
count_scissors = 0
count_paper = 0
count_r_w = 0
count_s_w = 0
count_p_w = 0
count_draw = 0
player = [] [3..100]

for i in 0..99 do
    puts "Please tell me how many people will play"
    num = gets.to_i
    for j in 1..num do
        player [i] [j] = rand (0..999)% 3
        if player [i] [j] == 0
            count_rock + = 1
        elsif player [i] [j] == 1
            count_scissors + = 1
        else
            count_paper + = 1
        end
        #puts "# {plyer [i] [j]}"
        if j == num
            if count_rock == num
                count_draw + = 1
            elsif count_scissors == num
                count_draw + = 1
            elsif count_paper == num
                count_draw + = 1
            elsif count_rock == 0&&count_scissors! = num
                count_s_w + = 1
            elsif count_scissors == 0&&count_paper! = num
                count_p_w + = 1
            elsif count_paper == 0&&count_rock! = num
                count_r_w + = 1
            else
                count_draw + = 1
            end
            count_rock = 0
            count_scissors = 0
            count_paper = 0
            puts ("# {j} people goo choki par draw")
            puts ("wins # {count_rock} times # {count_scissors} times # {count_paper} times # {count_draw} times")
            puts ("________________________________________________________________________")
        end
    end
end

I didn't know much about the declaration of a two-dimensional array and I looked into it, but the results remain unclear.

Supplemental information (FW/tool version etc.)
ruby ​​2.6.3p62 (2019-04-16 revision 67580) [x64-mingw32]


  • Answer # 1

    The 20th line is difficult to understand, but maybeplayer [i] [j] = rand (0..999)% 3? Player initialization is inadequate and player [i] reaches nil, and this error occurs.
    1. If player [i] = Ary.new within the range of .num, will it pass?

Related articles