2014-11-13 2 views
0

누군가이 2D 배열의 요소를 대체 할 수있는 방법을 말해 줄 수 있습니까? 나는 각각을 시험해 보았고, 포함하고 교체했고, 내가 어디로 잘못 가고 있는지 알 수 없었다. 사전에 도움을 주셔서 감사합니다.Ruby : 다차원 배열에서 일치하는 요소 바꾸기?

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 is #{@number}." 
    end 

    def has_number 
    #prints out initial slip 
     @lotto_slip.each {|x| p x} 

    #Prints slip with an "X" replacing number if is on slip 
    #Ex: @number equals 4th number on slip --> 1, 2, 3, X, 5, 6 
     @lotto_slip.each do |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 
+0

: 당신은'@lotto_slip = Array.new (5) {Array.new (6) {랜드 (1 쓸 수 .. 60)}}'. –

답변

1

이 밖으로 작동하는지 알려주세요 (쉽게 테스트 할 수 있도록하기 위해 10 일부터 변동을 줄이기 위해 시도) :

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 is #{@number}." 
    end 

    def has_number 
    #prints out initial slip 
    @lotto_slip.each {|x| p x} 

    #Prints slip with an "X" replacing number if is on slip 
    #Ex: @number equals 4th number on slip --> 1, 2, 3, X, 5, 6 
    @lotto_slip.each do |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 

난 당신의 코드를 본 문제는 다음과 같습니다 :

  • 당신은 어떻게 실제 문자열 배열에 의해 생성 된 숫자를 비교하려고, 다른 사람이 줄 @number = rand(1..60).to_s에 대한 to_s 필요하지 않습니다?

  • 다시 할당하는 대신 배열을 다시 생성해야합니다. 그 이유는 모든 코드를 기본적으로 전체 배열을 다시 생성하는 z.map! { |x| x == @number ? 'X' : x}으로 대체했기 때문입니다.

+0

신난다, 고마워. 구문과 올바른 방법을 사용하기 시작했습니다. 정말 도움을 주시면 고맙습니다. – Jinn

1

each에 필요한 반복 처리는 map을 사용하지 않습니다 : 제외

@lotto_slip = Array.new(5) {Array(6.times.map{rand(1..60)})} 
#=> [[25, 22, 10, 10, 57, 17], [37, 4, 8, 52, 55, 7], [44, 30, 58, 58, 50, 19], [49, 49, 24, 31, 26, 28], [24, 18, 39, 27, 8, 54]] 

@number = 24 
@lotto_slip.map{|x| x.map{|x| x == @number ? 'X' : x}} 
#=> [[25, 22, 10, 10, 57, 17], [37, 4, 8, 52, 55, 7], [44, 30, 58, 58, 50, 19], [49, 49, "X", 31, 26, 28], ["X", 18, 39, 27, 8, 54]] 
관련 문제