2014-10-22 77 views
0

我有一些困難,我的代碼,我希望一些見解:如何更換元素在多維數組中的紅寶石

我有一個二維數組的董事會和我試圖取代「若干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 

我知道,當驗證被稱爲它只能通過陣列1迭代,但我不知道該如何着手做修復。任何幫助讚賞。

回答

0

這是問題的根源:

@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] 

如果你希望所有的10S的更換,那麼這樣做:

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

考慮用'if if ndx = i.index(ball)'('=',而不是'==')替換'if i.include?(@ ball)'。 – 2014-10-22 13:47:30

+0

會做什麼,但你的意思是'ndx'? – daremkd 2014-10-22 13:50:30

+0

'ndx'將會是'nil'或等於下一行所需的索引。編寫'ndx = i.index(@ball)'可能會更好。 i.index(ndx)='X'if ndx; i'。 – 2014-10-22 14:00:41