Ruby:没有将nil隐式转换为Hash

时间:2016-09-23 20:42:27

标签: ruby-on-rails ruby

Ruby Rails新手有这个代码的问题(不是我写的)。我觉得这不应该太难,但是当我跑这个时,我就得到了 “没有将nil隐式转换为Hash”。我找不到关于此的好文档。提前谢谢!

这是我们的YAML:

current_colleges_for_degrees:
 cahs:
   label: 'College1'
 com:
   label: 'College2 '
additional_current_colleges:
   label: 'College3'
 a&s:
   label: 'College4'
 cob:
   label: 'College5'
library:
 library1: 'Library'

然后是our_helper文件: (相关部分)

def sorted_college_list_for_degrees
 COLLEGE_AND_DEPARTMENT["current_colleges_for_degrees"].keys.collect do |k|
  COLLEGE_AND_DEPARTMENT["current_colleges_for_degrees"][k]["label"]
 end.sort << "Other"
end


def sorted_college_list_for_degrees_with_library
 list = **(line 178)**COLLEGE_AND_DEPARTMENT["current_colleges_for_degrees"].merge(COLLEGE_AND_DEPARTMENT["library"][0])
    list.keys.collect do |k|
  [k]["label"]
end.sort << "Other"

def sorted_college_list_for_generic_works
   **(line 186)** sorted_college_list_for_degrees_with_library + COLLEGE_AND_DEPARTMENT["additional_current_colleges"]
end

最后,有一个使用它的表单:

<div class="span3">
 <%= f.input :college,
    collection: sorted_college_list_for_generic_works,
    selected: (curation_concern.college || current_user.college),
    input_html: { class: 'shrinking-form-input' },
    required: true,
    label: 'College' %>
</div>

这是应用程序跟踪的结果:

...Path/helpers/our_helper.rb:178:in `merge'
/Users/lisa/workspaces/curate/app/helpers/our_helper.rb:178:in`sorted_college_list_for_degrees_with_library'
/Users/lisa/workspaces/curate/app/helpers/our_helper.rb:186:in`sorted_college_list_for_generic_works'

2 个答案:

答案 0 :(得分:2)

好的,这是你的代码:

def sorted_college_list_for_degrees_with_library
 list = **(line 178)**COLLEGE_AND_DEPARTMENT["current_colleges_for_degrees"].merge(COLLEGE_AND_DEPARTMENT["library"][0])
    list.keys.collect do |k|
  [k]["label"]
end.sort << "Other"

def sorted_college_list_for_generic_works
   **(line 186)** sorted_college_list_for_degrees_with_library + COLLEGE_AND_DEPARTMENT["additional_current_colleges"]
end

错误消息是“没有将nil隐式转换为Hash”

这意味着Ruby方法(这里是Merge)期望一个哈希,但是你给它nil,它不知道该怎么做。

Merge需要两个哈希作为参数。在第187行的末尾,下面的代码看起来可能不是哈希:

(COLLEGE_AND_DEPARTMENT["library"][0])

尝试插入此内容:

puts COLLEGE_AND_DEPARTMENT["library"][0] 

在该行之前,看看该位的实际值是多少。我的猜测是“零”。如果该值是哈希值,请插入:

puts COLLEGE_AND_DEPARTMENT["current_colleges_for_degrees"]

查看是哈希还是零。我确定其中一个或两个都是零,然后你需要向后追踪,看看为什么它是零(错误标记的变量,一些以前的方法出错,等等)

有关MERGE的更多详细信息,请参阅HERE

最后,看起来方法“sorted_college_list_for_degrees_with_library”可能缺少“结束”。也许这只是剪切和粘贴,但看看原始代码,看它是否应该在那里。

答案 1 :(得分:0)

看起来COLLEGE_AND_DEPARTMENT["library"]像数组一样被使用,但它在YAML中被定义为散列。

COLLEGE_AND_DEPARTMENT["library"]    # => { library1: 'Library' }
COLLEGE_AND_DEPARTMENT["library"][0] # => nil

正如@CaptainChaos所说,合并需要给出哈希而不是nil。传递nil会导致no implicit conversion错误!

这可以通过更改YAML以将library定义为具有一个元素的数组来解决:

library:
  - label: 'Library'