replacing an element in nested array ruby

送分小仙女□ 提交于 2019-12-31 04:53:05

问题


I'm having trouble locating where my issue is in my code. I want to replace specific elements with 'X' if they show up on a bingo board:

class BingoBoard

  def initialize(board)
    @bingo_board = board
  end

  def number_letter

    @letter = ['B','I','N','G','O'].sample
    @number = rand(1..100)

  end

  def checker
    @number
    @bingo_board.map! do |n|

      if n.include?(@number)

        n.map! { |x| x == @number ? 'X' : x}

      else

        n

      end
    end

  end

end

this is the test i'm using to see if my code is running, but X never shows up and I been looking over my code many times now and can't figure out why...:

board = [[47, 44, 71, 8, 88],
        [22, 69, 75, 65, 73],
        [83, 85, 97, 89, 57],
        [25, 31, 96, 68, 51],
        [75, 70, 54, 80, 83]]

new_game = BingoBoard.new(board)

new_game.checker

If anyone can provide insight on what I am missing or not seeing, I would greatly appreciate it!


回答1:


class BingoBoard

  def initialize(board)
    @bingo_board = board
  end

  def number_letter

    @letter = ['B','I','N','G','O'].sample
    @number = rand(1..100)

  end

  def checker
    number_letter
    @bingo_board.each do |n|
      index = n.index(@number)
      n[index] = 'X' unless index.nil?
    end

  end

end


来源:https://stackoverflow.com/questions/29612258/replacing-an-element-in-nested-array-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!