How to replace element in multidimensional array in ruby -



How to replace element in multidimensional array in ruby -

i having difficulty code , hoping insight:

i have 2d array board , attempting replace number "x" when called, having struggles achieving this.

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 #{@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

i aware when verify called iterating through array1, unsure how go making fix. help appreciated.

this root of problem:

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

in example, array. might want replace code like:

@bingo_board.collect! |i| # you're iterating on double array here if i.include?(@ball) # single array, we're checking if ball number included i[i.index(@ball)] = 'x'; # find index of included element, replace x else end end

or if prefer one-liner:

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

be aware going replace first occurrence of element. so, if ball 10, , have:

[8, 9, 9, 10, 10]

you get:

[8, 9, 9, "x", 10]

if want of 10s replaced, like:

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

ruby arrays replace multidimensional-array

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -