Ruby: replacing a matching element in a multidimensional array? -


could tell me how can achieve replacing element in 2d array? tried each, include , replace , wasn't able figure out going wrong. thank in advance help.

class lotto    def initialize     @lotto_slip = array.new(5) {array(6.times.map{rand(1..60)})}   end    def current_pick     @number = rand(1..60).to_s     puts "the number #{@number}."   end    def has_number     #prints out initial slip       @lotto_slip.each {|x| p x}      #prints slip "x" replacing number if  on slip     #ex: @number equals 4th number on slip  --> 1, 2, 3, x, 5, 6       @lotto_slip.each |z|       if z.include?(@number)           z = "x"           p @lotto_slip       else           z = z           p @lotto_slip       end     end     end end    test = lotto.new test.current_pick test.has_number 

let me know if works out (tried reduce variations 1 10 in order able test easier):

class lotto    def initialize     @lotto_slip = array.new(5) {array(6.times.map{rand(1..10)})}   end    def current_pick     @number = rand(1..10)     puts "the number #{@number}."   end    def has_number     #prints out initial slip     @lotto_slip.each {|x| p x}      #prints slip "x" replacing number if  on slip     #ex: @number equals 4th number on slip  --> 1, 2, 3, x, 5, 6     @lotto_slip.each |z|       if z.include?(@number)         p "#{@number} included in #{z}"         z.map! { |x| x == @number ? 'x' : x}       end     end     @lotto_slip   end end    test = lotto.new test.current_pick p test.has_number 

the problems saw code are:

  • you don't need to_s line @number = rand(1..60).to_s, else how going compare numbers produced array actual string?

  • you need re-generate array instead of re-assigning, that's why i've replaced of code z.map! { |x| x == @number ? 'x' : x} re-generates entire array.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -