简体   繁体   English

Ruby 1.8.7符号数组引发TypeError:将符号作为数组索引

[英]Ruby 1.8.7 Array of symbols raising TypeError: Symbol as array index

I recently created a pull request for a gem which is building on travis against quite old ruby versions for backward compatibility. 我最近 travis上的宝石创建了一个拉取请求,该宝石是在travis上针对较旧的红宝石版本构建的,以实现向后兼容性。

In my commit I wanted to introduce a whitelist on some method options passed as an hash parameter. 在我的提交中,我想介绍一些作为哈希参数传递的方法选项的白名单。

In Rails with a recent ruby version it would look like: 在具有最新Ruby版本的Rails中,它看起来像:

MY_WHITELIST = %i(a b c)
def my_method(options={})
  @options = options.slice(*MY_WHITELIST)
end

In order to grant backward compatibility in a standalone gem, I provided a solution like: 为了授予独立gem的向后兼容性,我提供了以下解决方案:

MY_WHITELIST = [:a, :b, :c]
def my_method(options={})
  @options = options.select { |k, _| MY_WHITELIST.include?(k) }
end

This pass for ruby 1.9.3 but raise the following exception for 1.8.7 : 此通行证适用于红宝石1.9.3但针对1.8.7引发以下异常:

TypeError: Symbol as array index

According to the documentation , this way to initialise an array should be accepted. 根据文档 ,应采用这种初始化数组的方式。

Have you ever experienced with use? 您曾经使用过吗? What would you suggest? 你有什么建议?

如@mr_sudaca的评论所建议,解决方案是在数组上进行选择:

Hash[options.to_a.select { |k, _| MY_WHITELIST.include?(k) }]

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

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