【问题标题】:Ruby identical user defined functions return differentlyRuby 相同的用户定义函数返回不同
【发布时间】:2020-03-16 20:23:46
【问题描述】:

这些函数中只有一个('render' & 'render_all')打印到终端,而另一个返回“nil”。我可以交换它们,甚至使它们完全相同。一个将始终工作并打印,而另一个返回“nil”。我不知道为什么。我需要在最后显示我的 tile 类的所有面,这需要 render_all 并且我需要在游戏仍在播放时部分渲染它。

 class Board

  def initialize(size, bombs)
    @size = size 
    explosives = bombs
    @grid = Array.new(size) {Array.new(size) {Tile.new}}

    while explosives != 0
      potential_bomb = @grid[rand(0...size)][rand(0...size)]
      if potential_bomb.bomb == false
        potential_bomb.bomb = true
        potential_bomb.face = "X"
        explosives -= 1
      end
    end    
  end

  attr_accessor :size, :grid, 


   def render
    grid.each do |row|
      row.each do |box|
        if box.shown == true
          print "#{box.face}"
        else
          print "#"
        end        
      end
      print "\n"
    end
  end

  def render_all
    grid.each do |row|
      row.each do |box|
        print "#{box.face}"
      end
    end
  end

  def solved
    solved = true
    grid.each do |row|
        row.each {|pos| solved = false if pos.shown != true && pos.bomb == false}
    end
    return solved
  end

  def [](pos)
    x,y = pos
    grid[x][y]
  end
end

【问题讨论】:

  • 你可能想阅读stackoverflow.com/questions/58174877/…(虽然没有找到它不是你的错) - 始终启用警告!
  • FWIW,虽然它看起来像一个很好的欺骗候选人(问题相同,找到它,不是那么多),我犹豫是否将可能容易故意称为“错字” .我故意使用尾随逗号(在 Ruby 中不多,但有时)。

标签: ruby class user-defined-functions


【解决方案1】:
attr_accessor :size, :grid, 

看到结尾的逗号了吗?不好。

FWIW:任何时候出现与顺序相关的问题,总是立即查看上方;它通常与依赖顺序的事情无关,而是早先搞砸的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多