gpt4 book ai didi

ruby - 使用 `each` 检查所有值是否相同

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:27 26 4
gpt4 key购买 nike

我正在尝试评估每个空格值是否等于 "X""O"。我可以使用 each 来做到这一点吗?有没有更好的办法?

if @spaces.each {|x| x=="O" || x=="X"}
@winner = true
puts "It's a tie!"
break
end

预计到达时间:all? 似乎也不起作用。我在引用带有 block 的行时遇到此错误:

tictac.rb:47: syntax error, unexpected '|', expecting '}'
{|x| x=="O" || x=="X"}
^
tictac.rb:47: syntax error, unexpected '}', expecting keyword_end

这是我正在开发的整个 TicTacToe:

class Board
def initialize
@spaces = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.print_board
@winner = false
@turn = "X"
end

def print_board
puts
puts " " + @spaces[0].to_s + " " + @spaces[1].to_s + " " + @spaces[2].to_s
puts " " + @spaces[3].to_s + " " + @spaces[4].to_s + " " + @spaces[5].to_s
puts " " + @spaces[6].to_s + " " + @spaces[7].to_s + " " + @spaces[8].to_s
puts
end

def mark(turn, move)
space = @spaces.index(move)
@spaces[space] = turn
self.print_board
end

def play
while @winner == false
puts "where would you like to put your #{@turn}?"
move = gets.chomp.to_i
self.mark(@turn, move)
if
@spaces[0] == @turn && @spaces[1] == @turn && @spaces[2] == @turn ||
@spaces[3] == @turn && @spaces[4] == @turn && @spaces[5] == @turn ||
@spaces[6] == @turn && @spaces[7] == @turn && @spaces[8] == @turn ||
@spaces[0] == @turn && @spaces[3] == @turn && @spaces[6] == @turn ||
@spaces[1] == @turn && @spaces[4] == @turn && @spaces[7] == @turn ||
@spaces[2] == @turn && @spaces[5] == @turn && @spaces[8] == @turn ||
@spaces[0] == @turn && @spaces[4] == @turn && @spaces[8] == @turn ||
@spaces[2] == @turn && @spaces[4] == @turn && @spaces[6] == @turn

@winner = true
puts "#{@turn} is the winner!"
break
elsif @spaces.all?
{|x| x=="O" || x=="X"}
@winner = true
puts "It's a tie!"
break
else
@turn == "X"? @turn = "O" : @turn = "X"
end
end
end
end

game = Board.new
game.play

我标记了一个有效的答案,我想 all? 比我的 each 更好,但我仍然很好奇为什么要将它更改为 all? 似乎没有用。

最佳答案

@spaces.all? { |x| x=="O" || x=="X" }

您不能在方法调用和它的代码块之间放置换行符。这让 Ruby 认为您正在调用没有 block 的方法并定义哈希。

关于ruby - 使用 `each` 检查所有值是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26559042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com