在不使用实例变量ruby的情况下访问方法循环内部的变量

时间:2016-04-09 03:48:43

标签: ruby

如何在循环内访问player_1_symbol(和player_2_symbol)而不将其设置为实例方法。我正在尝试循环任何错误的输入,一旦它不在循环中我将调用new_method并需要传递player_1_symbol。

  def select_player_symbol(player_1, player_2)
    loop do
      puts "What symbol would you like #{player_1} to be?"
      player_1_symbol = gets.chomp

      puts "What symbol would you like #{player_2} to be?"
      player_2_symbol = gets.chomp

      if player_2_symbol != player_1_symbol
        puts "player 1: #{player_1_symbol}"
        puts "player_2: #{player_2_symbol}"
        break
      end
      puts "Please pick different symbols for each player"
    end
    new_method{player_1,
               player_2,
               player_1_symbol, 
               player_2_symbol}" # How to access these last two variables
  end

这是我的代码,但我想重构它。我不确定“更多”的正确方法是什么。但是,如果你不得不在一个循环之外调用一个变量,那么我真的很想知道未来如何在不将其设置为实例方法的情况下完成它。

  def select_player_symbol(player_1, player_2)
    puts "What symbol would you like #{player_1} to be?"
    player_1_symbol = gets.chomp

    puts "What symbol would you like #{player_2} to be?"
    player_2_symbol = gets.chomp

    while player_2_symbol == player_1_symbol
      puts "#{player_1} has already picked that symbol,"
      puts "please pick another symbol."
      player_2_symbol = gets.chomp
    end
    new_method{player_1,
               player_2,
               player_1_symbol, 
               player_2_symbol}
  end

2 个答案:

答案 0 :(得分:2)

在进入循环之前设置它,如:

  def select_player_symbol(player_1, player_2)
    player_1_symbol = nil
    player_2_symbol = nil
    loop do
      ...

这是有效的,因为通过建议的更改,player_1_symbol的范围是方法级别。在它的范围在循环内部之前。当你离开循环时,你失去了它。

答案 1 :(得分:-2)

在方法之外定义它们。 试一试HERE

$player_1_symbol = nil
$player_2_symbol = nil


def select_player_symbol(player_1, player_2)
    loop do
      puts "What symbol would you like #{player_1} to be?"
      $player_1_symbol = gets.chomp

      puts "What symbol would you like #{player_2} to be?"
      $player_2_symbol = gets.chomp

      if $player_2_symbol != $player_1_symbol
        puts "player 1: #{$player_1_symbol}"
        puts "player 2: #{$player_2_symbol}"
        break
      end
      puts "Please pick different symbols for each player"
    end
end

def another_method()
   puts "Gloabals are still here #{$player_1_symbol} and #{$player_2_symbol}"

end

#lets try it 
 select_player_symbol("Joe","Adam")
 another_method()