2010-03-22 113 views
1

我收到以下错误。麻烦与字典阵列,红宝石

 
game.rb:46:in `play': undefined method `[]' for nil:NilClass (NoMethodError) 
from game.rb:45:in `each' 
from game.rb:45:in `play' 
from game.rb:56 

与此代码,

def play() 
      currentTile = nil 
      @tiles.each do |tile| 
        if(tile['Name'] == 'Starting Square') 
          currentTile = tile 
        end 

        puts("#{currentTile['Desciption']}") 
      end 
end 

这是一个文字冒险游戏的一部分,我与@tiles打是被从文件中读取瓷砖的数组。每个瓷砖都是一本字典。

感谢您的帮助,我不能算出这个

+0

注意,在Ruby中,Python中所说的字典是这里称为哈希:) – Matchu 2010-03-22 22:49:41

回答

1

试试这个:

def play() 
    currentTile = nil 
    @tiles.each do |tile| 
    currentTile = tile if tile['Name'] == 'Starting Square' 
    puts("#{currentTile['Desciption']}") unless currentTile.nil? 
    end 
end 

你有一个错误,因为currentTile不是在第一个迭代成为了瓷砖。只有当瓷砖名称是'Starting Square'时才会得到'description'键

1

我看到你很可能试图通过印刷currentTile是否被设置尚未调试。所有的罚款和花花公子。

但是,请注意,直到名称匹配Starting SquarecurrentTile将继续nil,你不能访问nil对象的属性。也许起始平方不是列表中的第一个平铺?

0

看起来你试图在找到它之后打印currentTile的描述,但是你在放置搜索循环的时候会放入puts。

尝试:

def play() 
      currentTile = nil 
      @tiles.each do |tile| 
        if(tile['Name'] == 'Starting Square') 
          currentTile = tile 
        end 

      end 
      puts("#{currentTile['Desciption']}") 
end 

目前仍然不能保证你不会得到一个零引用(如果有名为“开始方块”无地砖,但你的代码将只工作如果@tiles中的第一个磁贴是标题为“Starting Square”的磁贴

0

其他答案似乎有你覆盖(将currentTile设置为零后编制索引),但无论它的价值如何,你都可能想成为使用符号来表示键和值,而不是字符串符号查找速度快,比较速度快,因为它们只是命名指针,而检查字符串eq uality是一个O(n)操作。

因此,像

def play() 
     currentTile = nil 
     @tiles.each do |tile| 
       if(tile[:name] == :startingSquare) 
         currentTile = tile 
       end 

     end 
     puts("#{currentTile['Desciption']}") unless currentTile.nil? 
end 

再说,我不知道您的应用程序,也许这是完全适当的^ _^