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

时间:2014-10-25 03:25:39

标签: ruby arrays

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

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

ETA:all?似乎也不起作用。我在引用块的行时出现此错误:

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?似乎不起作用。

3 个答案:

答案 0 :(得分:2)

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

您不能在方法调用及其块之间添加换行符。这使得Ruby认为你在没有阻塞和定义Hash的情况下调用该方法。

答案 1 :(得分:1)

如果<{p}},@spaces的所有元素都将是"O""X"

(@spaces - ["O", "X"]).empty?

是真的。

@spaces = ["O", "X", "X", "O"]
(@spaces - ["O", "X"]).empty?
  #=> true

@spaces = ["O", "X", "X", "O", "cat"]
(@spaces - ["O", "X"]).empty?
  #=> false

答案 2 :(得分:-1)

Chain Array#Uniq和Array#Size

将您的支票重构为一个方法,该方法采用一系列的条目(例如&#34; X&#34;或&#34; O&#34;),或者一个包含这种数组的变量。如果数组中的所有字母都相同,则该方法将返回true,因为只有一个唯一字符。例如:

def check_spaces letters
  true if letters.uniq.size == 1
end

check_spaces %w[X X X] #=> true
check_spaces %w[O O O] #=> true
check_spaces %w[O X O] #=> nil

如果你这样做,你甚至可以直接将#check_spaces的结果分配给 @winner ,如下所示:

@winner = check_spaces %w[X X X]
#=> true

@winner = check_spaces %w[X O X]
#=> nil