Assign symbols to variables in ruby -


a warrior class has methods walk,attack etc can pass direction. directions "symbols" ie :forward,:backward,:left,:right .

i trying save symbol ( :forward ) in instance variable ( @direction = :forward ) , use variable.and based on condition , change "direction" variable different symbol ( @direction = :backward ) . not seem work expected.it interpreted or somehow considered nil . here code tired 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 try use direction here , 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 missing symbols here ? understood "symbols" kind of immutable strings or in way enums faster.

i new ruby , have started https://www.bloc.io/ruby-warrior/ nice tutorial learn ruby got question. have tried searching not able find answer question.

when declare:

class player     @direction_to_go = :backward # <-- class instance variable      def reverse_direction       if @direction_to_go == :backward # <-- instance variable         @direction_to_go = :forward       else          @direction_to_go = :backward       end     end end 

you may refer ruby: class instance variables vs instance variables differences.

you should declare 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 

Comments