Where is my error in this Ruby code?

0

I'm having trouble with methods with parameter passing, the code runs, but it buga when I step to var within one method and receive as parameter in another. I'm new to Ruby.

def player_welcome
    puts "Seja bem vindo ao Jogo de Adivinhação !!"
    puts "Criado por Thiago De Bonis Carvalho Saad Saud"
end

def generate_number_raffled
    number_raffled = 100
    number_raffled.to_i
end

def player_choice_name
    puts "Qual seu nome jogador?"
    player_name = gets
    player_name.to_s
end

def player_choice_attempts(player_name)
    puts "Quantas tentativas gostaria de ter " + player_name + "?" 
    number_attempts = gets
    number_attempts.to_i
end

def play_the_game(player_name,number_attempts)
    puts " " + player_name + "você tem " + number_attempts + "."
    for player_attempts in 1..number_attempts
        puts "Adivinhe um número entre 0 e 200..."
        player_kick = gets
        if check_number_raffled(player_kick,number_raffled)
            break
        end
    end
    player_kick.to_i
end

def check_number_raffled(player_kick,number_raffled)
    if player_kick == number_raffled
        puts "Você Acertou !!"
        return true
    end
    if player_kick > number_raffled
        puts "Você errou!!"
        puts "Você digitou um número maior que o do Sorteado, tente novamente.."
    else
        puts "Você errou!!"
        puts "Você digitou um número menor que o do Sorteado, tente novamente.."
        end
end

player_welcome
player_choice_name
player_choice_attempts(player_name)
play_the_game(player_name,number_attempts)
    
asked by anonymous 14.10.2016 / 01:47

2 answers

1

player_name is a local variable. It exists only in method scope (player_choice_name)

If you do @player_name it is now an instance variable and is accessible by all methods within the class.

You can read more here: link

    
14.10.2016 / 03:32
1

As Gleyson has already said, player_name is a local variable of the player_choice_name method.

The solution is valid, but a better solution than creating instance variables is to get the method return, which method you have already prepared to return the player name with the player_name.to_s line, and assign that return to another variable, which will be passed as a parameter to the following methods:

def player_choice_name
  (...)
  player_name.to_s # Esse valor será retornado
end

(...)

player_welcome
player_name = player_choice_name
number_attempts = player_choice_attempts(player_name)
play_the_game(player_name, number_attempts)

Note that the number_attemps variable is also local and the same error would occur if the code arrived at the player_choice_attemps method call.

    
14.10.2016 / 06:18