代码之家  ›  专栏  ›  技术社区  ›  kortes

Ruby:在方法中调用“gets”方法保存Nil而不是Input

  •  1
  • kortes  · 技术社区  · 10 年前

    好了,伙计们,这是一个在终端上运行的地下城文本冒险项目。

    当用户说他想“北上”时,它会拆分字符串:第一个单词检查方法,第二个单词检查参数。这种情况发生在其他地方,我复制粘贴了导致以下问题的两个方法:

    当它调用go(north)并且north不是有效连接时,它会显示选项并再次询问用户方向,此时用户输入的输入由于某种原因存储为Nil。

    为什么?我还尝试了STDIN.gets.chomp.downase!结果相同

    代码如下:

        def find_room_in_direction(direction)
    
    ##-> if room connects with other on that direction, returns connection
    
            if find_room_in_dungeon(@player.location).connections.include?(direction.to_sym)
                return find_room_in_dungeon(@player.location).connections[direction.to_sym]
    
    ##-> if direction connection is not found, 
    ##-> show possible connections & return trigger to ask again inside go()
    
             elsif !find_room_in_dungeon(@player.location).connections.include?(direction.to_sym)
                 puts "I don't see any #{direction}..."
                 puts "This room only connects #{(find_room_in_dungeon(@player.location)).connections.keys.join(', ')}"
                 puts "Where should we go?"
    
                 return :redo
             end
             end
    
    
        def go(direction)
    
            current_direction = @player.location
            new_direction = find_room_in_direction(direction)
    
    ##-> if REDO trigger received, ask for new direction & try again
    
            if new_direction == :redo
                puts "REDOING DIRECTION"
    
        ##-> HERE IS THE PROBLEM:
        ##-> this does ask for input
    
                new_direction = gets.chomp.downcase!
    
    ##-> but it saves Nil instead of the input, so that puts shows ''
    
                puts "#{new_direction}"
    
    ##-> so this call trows an error: cant call method to Nil
    
                new_direction = find_room_in_direction(new_direction)
    
    ##-> if user entered valid direction from start, the following would run 
    
            elsif new_direction != :redo && current_direction != new_direction
                @player.location = new_direction
                puts "You go #{direction},"
                puts "and enter #{show_current_description}"
            end
            end
    

    有什么建议吗? 谢谢

    2 回复  |  直到 10 年前
        1
  •  5
  •   s-ol    10 年前

    您正在使用 downcase! 而不是 downcase . 放下! 在适当的位置更改字符串,如果没有更改,则返回nil(这就是这里发生的情况)。

    str = "teSt"
    puts str.downcase # test
    puts str # teSt
    str.downcase! 
    puts str # test
    

    看见 the documentation for downcase!

        2
  •  0
  •   iced    10 年前

    只是砰的一声。至于降级,有两种变体——chomp和chomp!

    推荐文章