each.cons没有返回任何东西

时间:2017-09-23 01:01:11

标签: ruby

我的win_vertical方法的第一部分将每个元素推送到一个新数组中。我已经把p'看看输出是怎么回事。当我运行代码时@column数组被填充,因为它应该在each_cons之后没有任何反应,没有错误并且不会打印任何内容。

class Board
    attr_accessor :board
    def initialize 
        @board = Array.new(6){Array.new(7," ")}
    end 


  def win_vertical
    @board.each do |element|
        @column = Array.new
        @column <<  element[2]
        p @column
        @column.each_cons(4) do |cons|
            p cons
            if cons == [["x"], ["x"], ["x"], ["x"]]
                puts "\n You win!"
                return true
            end
        end
    end
  end

end

1 个答案:

答案 0 :(得分:1)

我在@ board.each迭代开始后创建了数组,每次迭代都会生成一个新数组。在迭代之前创建新数组允许each_cons正常运行,因为它不会在单个元素数组上输出。

 def win_vertical
    @column = Array.new
    @board.each do |element|
        @column <<  element[2]
        p @column
        @column.each_cons(4) do |cons|
            p cons
            if cons == [["x"], ["x"], ["x"], ["x"]]
                puts "\n You win!"
                return true
            end
        end
    end
  end