2017-09-16 23 views
0

我不確定主題標題是否足夠具體,但在這裏。我有兩種方法 - 一種通過塊中的條件迭代一些數組來推送正確的數據。如何讓我的方法返回結果值爲第三種方法

下面是代碼

def iterate_lines 
    WIN_COMBINATIONS.each_with_index do |line,index| 
    lines = @board[line[0]] + @board[line[1]] + @board[line[2]] 
     if lines.include?("X") && !lines.include?("O") 
     scores = tally_scores(lines.count("X"),"X",index) 
      elsif lines.include?("O") && !lines.include?("X") 
     scores = tally_scores(lines.count("O"),"O",index) 
      elsif lines.include?("X") && lines.include?("O") 
     scores = tally_scores(0,"",index) 
      elsif !lines.include?("X") && !lines.include?("O") 
     scores = tally_scores(0,"",index) 
     end 
     p scores 
    end 
end 

另一種方法是將一個根據我所選擇的試探法計算這些分數。

def tally_scores(score,player,index) 
    score = 1 if score == 1 && player == "X" 
    score = -1 if score == 1 && player == "O" 
    score = 10 if score == 2 && player == "X" 
    score = -10 if score == 2 && player == "O" 
    score = 100 if score == 3 && player == "X" 
    score = -100 if score == 3 && player == "O" 
    score 
end 

呼喚「iterate_lines我可以打印出正確的價值觀出無論從‘tally_scores’,或者我在這裏表示,通過這些變量設定的分數「在呼叫‘iterate_lines’,這讓我剛從'iterate_lines'打印出來。

當然,'iterate_lines'的返回值是數組(WIN_COMBINATIONS)。硬編碼return scores顯然會給我只是最後一個值。

我的問題是我有第三種方法,需要得到'tally_scores'出來什麼,但我不能通過它作爲一個普通的參數,又名my_method(scores)。原因是第三種方法有它自己的參數列表,它因其他原因而被傳遞。另外,直到該方法被調用時纔會是零。

def get_scores 
    # other code 
    #: something like this: 
    score = iterate_lines 
    # or 
    score = tally_scores 
    # or 
    # ? 
end 

因此,我覺得我可能會將自己置於一個角落,並應該摧毀我擁有的東西並重新開始。我會說我嘗試了'tally_scores'並將分數放入一個實例變量數組中。我發現,雖然當我通過它時,除最後一個值之外的所有值都保留。

+0

從未傷害時,你有什麼要使用明確的'return'喜歡這個。 –

+0

當然,我試過明確的回報,但沒有讓我到任何地方。我的意思是,它爲我做的只是獲得一個價值。 – stuartambient

+0

這是井字遊戲嗎?如果是的話我無法弄清楚你正在做的事情,部分原因是一些代碼丟失('WIN_COMBINATIONS'和'@ board')。一些觀察:1)塊變量'index'沒有被使用; 2),而不是方法'talley_scores'可以使用哈希'{[1, 「X」] => 1,[1, 「O」] => - 1,[2, 「X」] => 10, [2,「O」] => - 10,[3,「X」] => 100,[3,「X」] => - 100} 3)它可能是最好的行,列和對角線計數'「X」'的'和‘O’'的啓動,4)如果TTT,計算分數似乎是一個奇怪的做法。 –

回答

1

這裏有幾個問題。首先,正如您在使用each_with_index時看到的那樣,除非您使用副作用,否則該塊中發生的任何事情都不會在外面產生影響。如果你在該塊中設置了一個變量,它將在每次迭代中重置。

您可以將其更改爲map.with_index,以便結果是由迭代產生的結果數組。

而且好像scores應該score在這裏和它相似的線條,因爲tally_scores返回一個分數:如果您使用map.with_index

scores = tally_scores(lines.count("X"),"X",index) 

,那麼該塊的返回值應該是score,這樣的結果將是一系列的分數。但是,您不能使用該塊中的return score,該塊將從父項方法返回,而不是單個塊的迭代。您可以使用next score替代或簡單地使用score作爲最後一行。

做出這些更改後,您可以說scores = iterate_lines

這將是這個樣子:

def iterate_lines 
    WIN_COMBINATIONS.map.with_index do |line, index| 
    # set score according to your conditional logic 
    score # or alternatively, "next score" 
    end 
end 

這是更好地打印邏輯提取到其他地方,例如:

scores = iterate_lines 
scores.each { |score| p score } 
+0

很棒!我有一種感覺,地圖會很有用,但我不知道'map.with_index'是可能的。 – stuartambient