如何根据条件语句更新hashmap值

时间:2017-11-20 17:09:26

标签: ruby hashmap

我需要帮助更新我的HashMap的值。想法是用户将Rover Direction输入为N.然后用户将行为输入为L(左侧)。 move_left方法然后将Hashmap键“D”更新为等于“W”而不是用户输入的“N”。但是,这段代码不会将其更新为“W”。任何帮助都会很棒。我是一个绝对的初学者,所以任何建议都会很棒!

def rover_direction
  puts " \n Please input the direction which the rover is facing 
 (N,E,S,W):    "
 user_input = gets.chomp.upcase
 @direction = {"D" => user_input}
end

def rover_behaviour
  puts " \n Please input the behaviour of the rover(L,R & M):    "
  input = gets.chomp.upcase
  @behaviour = input.scan /\w/

  if @behaviour[0] == "L" 
    move_left
  elsif @behaviour[0] == "R" 
    move_right
  elsif @behaviour[0] == "M"
    move_forward
  end
end

#move rover left as per behaviour input
def move_left
  if @direction[0] == "N"  
    @direction.update("D") { |key, user_input| user_input == W }
  elsif @direction[0] == "W"
    @direction.update("D") { |key, user_input| user_input == "S" }
  elsif @direction[0] == "S"
    @direction.update("D") { |key, user_input| user_input == "E" }
  elsif @direction[0] == "E"
    @direction.update("D") { |key, user_input| user_input == "N" }
  end
end

0 个答案:

没有答案