2012-10-17 36 views
0

我有一个哈希包括:未定义的方法[]为无:NilClass在红宝石哈希

flow = ["a", "b", "c"] 
h = [{"case_id"=>1, "a"=>{"x"=>"text", "option"=>"..." },"b"=>{"report"=>"text", "option"=>"..." } ,"c"=>{"y"=>"text", "option"=>"..." }},{"case_id"=>2, "a"=>{"x"=>"text", "option"=>"..." },"b"=>{"report"=>"text", "option"=>"..." } ,"c"=>{"y"=>"text", "option"=>"..." }}] 
@case = 0 
@report = "" 
flow.each do |step| 
    if h[@case][step]['report'] 
    @report = h[@case][step]['report'] 
    end 
end 

控制台使我有以下错误:

NoMethodError in MainController#index 
undefined method `[]' for nil:NilClass 

为什么?在之前的程序中,但使用红宝石187,没有问题。但现在,红宝石193,给出了这个错误。

+0

您可以编辑您的问题提供了一些伟大的迭代帮手。 –

+0

在'h''前面有两个逗号,“c”' – PriteshJ

+0

是不是这个错误,写入错误。对不起 –

回答

1
flow = ["a", "b", "c"] 
h = { "a"=>{"x"=>"text", "option"=>"..." },"b"=>{"report"=>"text", "option"=>"..." } ,"c"=>{"y"=>"text", "option"=>"..." }} 
flow.each do |f| 
    if h[f]['report'] 
    #something 
    end 
end 

Ruby有通过枚举类

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-each

+0

同样的错误:( –

+0

@SimoneMazzotta你复制粘贴整个代码? – PriteshJ

+0

不,你等待重写代码。谢谢反正你给我的帮助;) –

0

直到hh[a]nil,您都不会收到错误。请正确更新您的问题。

+0

我刷新了代码... –

+1

不应该这是一个评论,而不是一个答案? – Mischa