简体   繁体   中英

Assign symbols to variables in ruby

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM