我想做一个TicTacToe游戏。我尝试定义一个将空白字段更改为'X'
或'O'
的实例方法。
class TicTacToe
attr_accessor :fields, :a1, :a2, :a3, :b1, :b2, :b3, :c1, :c2, :c3
def initialize
@a1,@a2,@a3 = " ", " ", " "
@b1,@b2,@b3 = " ", " ", " "
@c1,@c2,@c3 = " ", " ", " "
@fields = {a1: @a1, a2: @a2, a3: @a3, b1: @b1, b2: @b2, b3: @b3, c1: @c1, c2: @c2, c3: @c3}
end
def print_table
p "#{@fields[:c1]}|#{@fields[:c2]}|#{@fields[:c3]}"
p "#{@fields[:b1]}|#{@fields[:b2]}|#{@fields[:b3]}"
p "#{@fields[:a1]}|#{@fields[:a2]}|#{@fields[:a3]}"
p '# # #'
end
end
game = TicTacToe.new
game.print_table #=> fields[:a1] == ' '
def to_x field
field = "Y"
end
p to_x game.fields[:a1] #=> fields[:a1] == 'Y'
game.print_table #=> fields[:a1] == ' '
game.fields[:a1] = "X" #=> fields[:a1] == 'X'
game.print_table #=> fields[:a1] == 'X'
当我将字符串或哈希对象传递给它时,Ruby会引发错误。我想反过来在一个对象上调用我的方法:
field[:a1].to_x
我该怎么做?
我还尝试在类之外提取一个方法,并将对象传递给它,但我无法更改变量值。我猜ruby会创建另一个引用相同对象的对象。
我做错了什么,以及做这件事的正确方法是什么?
答案 0 :(得分:0)
Ruby中的字符串是可变的:
s = "X"
# => "X"
s[0] = "O"
# => "O"
s
# => "O"
所以你可以写:
def to_x field
field[0] = "X"
end
def to_o field
field[0] = "O"
end
to_x game.fields[:a1]
game.print_table
# " | | "
# " | | "
# "X| | "
# "# # #"
to_o game.fields[:a1]
game.print_table
# " | | "
# " | | "
# "O| | "
# "# # #"