【问题标题】:How to replace element in multidimensional array in ruby如何在ruby中替换多维数组中的元素
【发布时间】:2014-12-17 19:53:33
【问题描述】:

我的代码有一些困难,我希望得到一些见解:

我有一个板的二维数组,我试图在调用时用“X”替换一个数字,但我很难实现这一点。

class BingoBoard

  def initialize
    @bingo_board = Array.new(5) {Array (5.times.map{rand(1..100)})}
    @bingo_board[2][2] = 'X'
  end

  def new_board
  @bingo_board.each{|row| p row}
end

def ball
  @letter = ["B","I","N","G","O"].shuffle.first
  @ball = rand(1..100)
  puts "The ball is #{@letter}#{@ball}"
end


def verify
  @ball
  @bingo_board.each{|row| p row}
  @bingo_board.collect! { |i| (i == @ball) ? "X" : i}
  end
end


newgame = BingoBoard.new
puts newgame.ball
newgame.verify

我知道,当调用 verify 时,它只会遍历 array1,但我不确定如何进行修复。任何帮助表示赞赏。

【问题讨论】:

    标签: ruby arrays replace multidimensional-array


    【解决方案1】:

    这是问题的根源:

    @bingo_board.collect! { |i| (i == @ball) ? "X" : i}
    

    在本例中,i 是一个数组。所以你可能想要做的是用类似的东西替换你的代码:

    @bingo_board.collect! do |i| # you're iterating over a double array here
       if i.include?(@ball) # i is a single array, so we're checking if the ball number is included
         i[i.index(@ball)] = 'X'; i # find the index of the included element, replace with X
       else
         i
       end
    end
    

    或者,如果您更喜欢单线:

    @bingo_board.collect! { |i| i.include?(@ball) ? (i[i.index(@ball)] = 'X'; i) : i }
    

    请注意,这只会替换第一次出现的元素。所以,假设你的球是 10,你有:

    [8, 9, 9, 10, 10]
    

    你会得到:

    [8, 9, 9, "X", 10]
    

    如果您想替换所有 10 个,请执行以下操作:

    @bingo_board.collect! do |i|
      if i.include?(@ball)
        i.collect! { |x| x == @ball ? 'X' : x }
      else
        i
      end
    end
    

    【讨论】:

    • 考虑将 'if i.include?(@ball)` 替换为 if ndx = i.index(ball)=,而不是 ==)。
    • 会做,但'ndx'是什么意思?
    • ndx 将是 nil 或将等于您在下一行中需要的索引。写ndx = i.index(@ball); i.index(ndx) = 'X' if ndx; i 可能更好。
    • 感谢daremkd的方法确实解决了问题。
    猜你喜欢
    • 2019-10-14
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2017-11-10
    • 1970-01-01
    • 2021-08-23
    相关资源
    最近更新 更多