Reputation: 703
A warrior class has methods like walk,attack etc to which we can pass the direction. The directions are "symbols" ie :forward,:backward,:left,:right .
I am trying to save the symbol ( say :forward ) in an instance variable ( say @direction = :forward ) and use the variable.And based on some condition , I will change the "direction" variable to a different symbol ( say @direction = :backward ) . However this does not seem to work as expected.It is interpreted or somehow considered as nil . Here is the code that I tired to write
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
Am I missing something about symbols here ? I understood that "symbols" are kind of immutable strings or in a way enums which are faster.
I am new to ruby and have started this https://www.bloc.io/ruby-warrior/ nice tutorial to learn ruby where I got this question. I have tried searching about this but was not able to find any answer to my question.
Upvotes: 1
Views: 2131
Reputation: 1565
When you declare:
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
You may refer to ruby: class instance variables vs instance variables for the differences.
You should declare like this:
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
Upvotes: 6