简体   繁体   English

Ruby错误帮助,枚举器

[英]Ruby Error Help, Enumerator

I have some code that worked locally but when it ran RSPEC on the server I had a build fail. 我有一些在本地工作的代码,但是当它在服务器上运行RSPEC时,构建失败。

Here is my code: 这是我的代码:

def sort_software_list(software_list)
  pkgs = JSON.load(File.read("#{Rails.root}/lib/tasks/pkgs.json"))
  hash = pkgs.map { |e| e["name"] }.each_with_index.to_h
  sorted_list = software_list.sort_by { |e| hash[e.name]}
  sorted_list
end

It takes a file in the Rails project which is just a json file. 它需要在Rails项目中的一个文件,它只是一个json文件。 The function takes in software_list and sorts it with the correct order that the json file is in. 该函数接收software_list并按照json文件所在的正确顺序对其进行排序。

So my error on the failing rspec is: 所以我对失败的rspec的错误是:

undefined method `to_h' for #<Enumerator:0x0000000db66b30>

I am having trouble thinking of a reason this is happening. 我很难想到发生这种情况的原因。 Like I said it is working locally as far as I can tell. 就像我说的那样,据我所知,它在本地工作。 Any thoughts? 有什么想法吗?

I'm willing to bet that your local machine has Ruby 2.1.0 or greater and your server has a lesser version. 我敢打赌,您的本地计算机具有Ruby 2.1.0或更高版本,而您的服务器具有较低的版本。 Enumerator didn't get a to_h method (via Enumerable) until Ruby 2.1.0. 直到Ruby 2.1.0,Enumerator才获得to_h方法(通过Enumerable)。 An easy workaround is to use the Hash.[] method instead, after converting the Enumerator to an Array: 一个简单的解决方法是在将枚举器转换为数组后,使用Hash.[]方法代替:

hash = Hash[ pkgs.map {|e| e["name"] }.each_with_index.to_a ]

You may also find it useful to manage your project's Ruby version with rbenv or RVM to ensure that you're using the same version in development and in production. 您可能还会发现使用rbenv或RVM管理项目的Ruby版本以确保在开发和生产中使用相同的版本很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM