无法向阵列添加元素

时间:2015-03-05 12:17:09

标签: ruby

我正在制作一个Yhatzee游戏,并且我遇到了一个非常类似的问题,之前我已经设法解决了这个问题,但这个我似乎无法理解。如果这是一个菜鸟问题,请原谅我...我是菜鸟。

class  Yhatzee
  def dices
    @dice = Array.new(5){rand(1..6)}
  end

  def roll_dice
    puts dices
  end

  def dice_choice
    puts "do you want to keep any of the dices type 1-5 or 0 if you don't  want to keep any.?"

    keep_dice = gets.to_i

    if @dice[0] == keep_dice
      puts "#{keep_dice} keeping"
      @dice_log << keep_dice
    elsif @dice[1] == keep_dice
      puts "#{keep_dice} keeping"
      @dice_log << keep_dice
    elsif @dice[2] == keep_dice
      puts "#{keep_dice} keeping"
      @dice_log << keep_dice
    elsif @dice[3] == keep_dice
      puts "#{keep_dice}keeping"
      @dice_log << keep_dice
    elsif @dice[4] == keep_dice
      puts "#{keep_dice} keeping"
      @dice_log << keep_dice
    else
      puts "didn't work..."
    end
  end

  def dice_log
    @dice_log = Array.new(0)
    puts @dice_log
  end
end

x = Yhatzee.new
puts x.roll_dice
puts x.dice_choice

我得到的错误是

`dice_choice': undefined method `<<' for nil:NilClass (NoMethodError)

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

这是因为您尝试使用尚未定义的@dice_log。这会导致<<缺少nil方法的错误。

您可以执行的简单操作是initialize Yhatzee@dice_log = Array.new(0)一样:

class  Yhatzee
  def initialize
    @dice_log = Array.new(0)
  end
  # ...
end

这将导致错误undefined method<<' for nil:NilClass (NoMethodError)消失。

还有一件事 - 从@dice_log = Array.new(0)方法移除dice_log。它会覆盖您@dice_log中存储的内容。

希望有所帮助!