0

我有一个哈希,包括:

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

为什么?!在以前的程序中,但使用 ruby​​ 187,没有问题。但是现在,用ruby 193,给出了这个错误。

4

2 回答 2

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

于 2012-10-17T12:47:07.343 回答
0

h在or 或h[a]is之前,您不会得到错误nil。请正确更新您的问题。

于 2012-10-17T12:20:14.663 回答