Wednesday, 15 February 2012

ruby - Using `each` to check whether all values are the same -



ruby - Using `each` to check whether all values are the same -

i'm trying evaluate whether every space value equal either "x" or "o". can utilize each that? there improve way?

if @spaces.each {|x| x=="o" || x=="x"} @winner = true puts "it's tie!" break end

eta: all? doesn't seem working, either. got error referring line block:

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

here entire tictactoe i'm working on:

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 set #{@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} winner!" break elsif @spaces.all? {|x| x=="o" || x=="x"} @winner = true puts "it's tie!" break else @turn == "x"? @turn = "o" : @turn = "x" end end end end game = board.new game.play

i marked reply worked, , guess all? improve each, i'm still curious why changing all? didn't seem work.

all elements of @spaces "o" or "x" if

(@spaces - ["o", "x"]).empty?

is true.

@spaces = ["o", "x", "x", "o"] (@spaces - ["o", "x"]).empty? #=> true @spaces = ["o", "x", "x", "o", "cat"] (@spaces - ["o", "x"]).empty? #=> false

ruby arrays

No comments:

Post a Comment