战士类有散步,攻击等方法,我们可以通过这些方法.方向是"符号",即:向前,向后,向左,向右.
我试图在实例变量(比如说@direction =:forward)中保存符号(例如:forward)并使用变量.根据某些条件,我将"方向"变量更改为不同的符号(比如@方向=:向后).然而,这似乎没有按预期工作.它被解释或以某种方式被视为零.这是我厌倦写的代码
class Player
@direction_to_go = :backward # default direction
def reverse_direction
if @direction_to_go == :backward
@direction_to_go = :forward
else
@direction_to_go = :backward
end
end
def actual_play(warrior,direction)
# attack
# walk
# rest
# When I try to use direction here , its nil !?
end
def play_turn(warrior)
if warrior.feel(@direction_to_go).wall?
reverse_direction
end
actual_play(warrior,@direction_to_go)
end
end
Run Code Online (Sandbox Code Playgroud)
我在这里遗漏了一些符号吗?我理解"符号"是一种不可变的字符串,或者是一种更快的枚举.
我是ruby的新手,已经开始使用这个https://www.bloc.io/ruby-warrior/很好的教程来学习ruby,我得到了这个问题.我试过搜索这个,但无法找到我的问题的任何答案.
当你声明:
class Player
@direction_to_go = :backward # <-- this is class instance variable
def reverse_direction
if @direction_to_go == :backward # <-- this is instance variable
@direction_to_go = :forward
else
@direction_to_go = :backward
end
end
end
Run Code Online (Sandbox Code Playgroud)
您可以参考ruby:类实例变量与实例变量的差异.
你应该这样声明:
class Player
def initialize
@direction_to_go = :backward
end
def reverse_direction
if @direction_to_go == :backward
@direction_to_go = :forward
else
@direction_to_go = :backward
end
end
end
Player.new.reverse_direction
Run Code Online (Sandbox Code Playgroud)