2017-09-16 38 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